I recently researched the solution for a palindrome problem using Javascript.
There is one particular line of code that I am struggling to comprehend, and I'm hoping someone can shed some light on it for me.
Here is the code snippet in question:
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 am particularly confused about why the condition in the "while" loop is set as
while( fast && fast.next)
Initially, I tried using while(fast.next)
and encountered an error stating that I cannot access 'next' of null. This led me to wonder why fast && fast.next
works instead.