Skip to content

Files

Latest commit

 

History

History
41 lines (36 loc) · 1.03 KB

234. Palindrome Linked List.md

File metadata and controls

41 lines (36 loc) · 1.03 KB

Screen Shot 2022-08-22 at 17 10 49

/**
 * 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;
}