LeetCode(234) 判断一个链表是否为回文链表

378 阅读1分钟

请判断一个链表是否为回文链表

Palindrome Linked List

Given a singly linked list, determine if it is a palindrome.

Follow up: Could you do it in O(n) time and O(1) space?

关键技巧:空链表,只有一个节点,两个节点一模一样的都算回文,利用快慢指针移动到中间节点,然后再往后移动一个节点,反转后半部分的节点,和前半部分的节点一一对比,以后半部分遍历结束为准。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isPalindrome(ListNode head) {
        if (head == null) {
            return true;
        }
    
        ListNode quick = head;
        ListNode slow = head;
        while (quick.next != null && quick.next.next != null) {
            quick = quick.next.next;
            slow = slow.next;
        }
        
        slow = slow.next; //注意往后移动一个
        
        //slow进行一波链表反转
        ListNode preNode = null;
        ListNode current = slow;
        ListNode nextNode = null;
        while (current != null) {
            nextNode = current.next;
            current.next = preNode;
            preNode = current;
            current = nextNode;
        }
        while (preNode != null) {
            if (preNode.val != head.val) {
                return false;
            }
            preNode = preNode.next;
            head = head.next;
        }
        return true;
    }
}
  • 时间复杂度:O(n)O(n),其中 nn 指的是链表的大小。
  • 空间复杂度:O(1)O(1),我们是一个接着一个的改变指针,我们在堆栈上的堆栈帧不超过 O(1)O(1)。

还有一个方法就是,把链表值遍历放到数组中,然后数组中一个从前往后,一个从后往前,进行对比,但是空间复杂度为O(n)。