
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function isPalindrome(head: ListNode | null): boolean {
let slow = head, fast = head;
while(fast.next && fast.next.next) {
slow = slow.next;
fast = fast.next.next;
}
slow.next = reverse(slow.next);
slow = slow.next;
while(slow) {
if(slow.val !== head.val) return false;
slow = slow.next;
head = head.next;
}
return true;
};
function reverse(head) {
let [prev, current] = [null, head];
while(current) {
[current.next, prev, current] = [prev, current, current.next];
}
return prev;
}