leetcode 234 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?


  • using two pointers:
    • A slow pointer with step length equals One
    • A fast pointer with step length eauqls Two
  • We can get the middle elements pointed by slow when the total number of the array is odd.
  • Slow pointer points at the larger one when the array is at a length of even.
  • We can implements an function which reverses the linked list, So we can get the reverse list over [slow, -1].
  • compare head with slow step by step until slow points to null.
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

* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class {
public boolean isPalindrome(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
slow = reverse(slow);
while(slow!=null){
if(slow.val != head.val){
return false;
}
head = head.next;
slow = slow.next;
}
return true;
}
public ListNode reverse(ListNode head){
ListNode prev = null;
while(head != null){
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
}