LeetCode-in-All

234. Palindrome Linked List

Easy

Given the head of a singly linked list, return true if it is a palindrome or false otherwise.

Example 1:

Input: head = [1,2,2,1]

Output: true

Example 2:

Input: head = [1,2]

Output: false

Constraints:

Follow up: Could you do it in O(n) time and O(1) space?

Solution

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {boolean}
 */
var isPalindrome = function(head) {
    let len = 0
    let right = head

    while (right !== null) {
        right = right.next
        len++
    }

    len = Math.floor(len / 2)
    right = head
    for (let i = 0; i < len; i++) {
        right = right.next
    }

    let prev = null
    while (right !== null) {
        let next = right.next
        right.next = prev
        prev = right
        right = next
    }

    for (let i = 0; i < len; i++) {
        if (prev !== null && head.val === prev.val) {
            head = head.next
            prev = prev.next
        } else {
            return false
        }
    }
    return true
};

export { isPalindrome }