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?

O(n) time, O(1) extra space

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/

public class Solution {
public boolean isPalindrome(ListNode head) {
// Note: the input will be changed, which is considered as a bad practice
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode slow = dummy;
ListNode fast = dummy;
// The above 4 lines can be replaced by the following 3 lines
// if (head == null) return true;
// ListNode slow = head;
// ListNode fast = head.next;

// find the middle point
while (fast != null && fast.next !=null) {
slow = slow.next;
fast = fast.next.next;
}
// reverse the latter half, then compare the value from two ends to the middle point
ListNode end = reverseLinkedList(slow.next);
while (head != null && end != null) {
if (head.val != end.val) {
return false;
} else {
head = head.next;
end = end.next;
}
}
return true;
}

public ListNode reverseLinkedList(ListNode head) {
ListNode prev = null;
while (head != null) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
}