/**
* 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) {
if (head == null || head.next == null) return true;
ListNode prev = null;
ListNode next = null;
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null )
{
// fast and slow pointers need to move before reverse the first half of the list. Otherwise, as the list is reversed, pointer of the next node has changed, which will affect the iteration of the fast and slow pointers.
fast = fast.next.next;
slow = slow.next;
next = head.next;
head.next = prev;
prev = head;
head = next;
}
if(fast != null ) // odd
slow = slow.next;
while(prev != null)
{
if (slow.val != prev.val) return false;
// if the problem cares about the original list, we can reverse the first half back as we compare.
slow = slow.next;
prev = prev.next;
}
return true;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
private ListNode reverse(ListNode head) {
ListNode newHead = null;
while (head != null) {
ListNode next = head.next;
head.next = newHead;
newHead = head;
head = next;
}
return newHead;
}
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) return true;
ListNode fast = head, slow = head;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
slow = slow.next;
}
fast = head;
slow = slow.next;
ListNode newHead = reverse(slow);
while (newHead != null) {
if (newHead.val != fast.val) return false;
newHead = newHead.next;
fast = fast.next;
}
return true;
}
}