234. Palindrome Linked List

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

Example 1:

1
2
Input: 1->2
Output: false

Example 2:

1
2
Input: 1->2->2->1
Output: true

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public class Solution {
    public boolean isPalindrome(ListNode head) {
        ListNode point = head;
        Stack<Integer> s = new Stack<>();
        while(point!=null){
            s.push(point.val);
            point = point.next;
        }
        while (head!=null){
            if (head.val!=s.pop()){
                return false;
            }
            else{
                head = head.next;
            }
        }
        return true;
    }
}

首先想到的是堆栈法: - 先全部压如栈,再一个个弹出来比较 - 显然效率不高,遍历了两次

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class Solution {
    public boolean isPalindrome(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while(fast!=null&&fast.next!=null){
            fast = fast.next.next;
            slow = slow.next;
        }
        if (fast!=null){
            slow = slow.next;//这个地方不要可以,可以少遍历一个数
        }
        slow = reverse(slow);
        fast = head;
        while(slow!=null){
            if (slow.val!=fast.val){
                return false;
            }
            slow = slow.next;
            fast = fast.next;
        }
        return true;
    }
    private ListNode reverse(ListNode head){
        ListNode result = null;
        while(head!=null){
            ListNode point = head;
            head = head.next;
            point.next = result;
            result = point;
        }
        return result;
    }
}

然后是效率较高的快慢指针法: - 总体应该是遍历1.5次(不确定) - 利用快慢指针先对半分,然后把后半部分逆序,与前半部分一一比较 - 对于逆序的head = head.next;point.next = result;有顺序要求,head得先操作跑掉,否则point的操作影响了head