Journal Archive

/**
 * 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) {
    
    function reverse(head) {
        let tail = null;
        let current = head;
        
        while(current) {
            let next = current.next
            current.next = tail;
            tail = current;
            current = next;
        }
        return tail;
    }
    
    // using fast and slow pointer to find middle
    let fastP = head;
    let slowP = head;
    
    while(fastP.next && fastP.next.next) {
        fastP = fastP.next.next;
        slowP = slowP.next;
    }
    
    // set slow pointer to be the second half
    slowP = slowP.next;
    fastP = head;
    slowP = reverse(slowP);
    
    
    // check for palindrome
    while(slowP) {
        if(slowP.val !== fastP.val) return false;
        slowP = slowP.next;
        fastP = fastP.next;
    }
    
    return true;
    
    
};

Day 23: Solving one of LeetCode problems

234. Palindrome Linked List Difficulty - Easy

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

 

Example 1:

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

Example 2:

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