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
class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null)
return true;
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode prev = null;
ListNode curr = slow;

// Reverse the right half list.
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}

// Two pointers. One from the left, the other from the right.
ListNode left = head;
ListNode right = prev;
while (right != null) {
if (left.val != right.val)
return false;
left = left.next;
right = right.next;
}
return true;
}
}

这道题在于slow和fast, 如果fast跑到最后, slow的位置在哪里? 这是关键. 如果是偶数个node, slow最终会在后一半第0个node处. 如果是奇数个则刚好在正中间那个.

时间复杂度: O(n)
空间复杂度: O(1)