Thomaswasalone
Thomaswasalone

Reputation: 63

Linked List Palindrome Leet Code Solution in Javascript

I have looked up the solution for the palindrome question in Javascript.

There is a line of code that I dont really understand and I hope someone can enlighten me.

Here is the solution:

this.palindrom = function() {
            //two pointers to find the middle 
            // 1 slow pointer - move 1 at a time
            // 1 fast pointer - move 2 at a time 

        let slow = this.head
        let fast = this.head
        let start = this.head
        console.log('fast', fast)
        let length = 0 
       
        while( fast && fast.next) {
            fast = fast.next.next
            slow = slow.next 
            start = start.next
            length++
        }
        console.log(slow)
       let mid = this.reverse(slow)
        console.log('mid',mid)
        while (length !== 0) {
            length --
            if (mid.data !== start.data) return false 
            else return true 
        }

      }
    }

I do not understand why the parameters of the "while" loop is

while( fast && fast.next)

i typed while(fast.next) and there was an error saying cannot access null of next. I am wondering why fast && fast.next works instead.

Upvotes: 0

Views: 132

Answers (1)

trincot
trincot

Reputation: 350766

fast && fast.next is applying a safeguard to fast being null. If fast is null, then it would be an error to evaluate fast.next -- which is what you experienced when you "simplified" the condition.

If fast is null then the expression fast will be "falsy", and because of how the && operator works (short-circuiting), the evaluation will then stop and not attempt to evaluate fast.next. Instead it will consider the whole expression to be falsy, and exit the loop.

Upvotes: 0

Related Questions