/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
// edge cases
if (head == null || head.next == null) return true;
// 2 pointers
ListNode slow = head.next, fast = head.next.next, r = head, prev = null;
int cnt = 2;
while (fast != null && fast.next != null) {
fast = fast.next.next;
cnt += 2;
// reverse
r.next = prev;
prev = r;
r = slow;
slow = slow.next;
}
r.next = prev;
if (fast != null) cnt++;
// check
ListNode left = r, right = cnt % 2 == 0 ? slow : slow.next;
while (left != null && right != null) {
if (left.val != right.val) return false;
left = left.next;
right = right.next;
}
return true;
}
}