I am working on a problem to determine whether a linked list is a Palindrome (Leetcode 234). I came across this (way above my level) solution.
var isPalindrome = function(head) {
let slow = head, fast = head, prev, temp
while (fast && fast.next)
slow = slow.next, fast = fast.next.next
prev = slow, slow = slow.next, prev.next = null
while (slow)
temp = slow.next, slow.next = prev, prev = slow, slow = temp
fast = head, slow = prev
while (slow) {
if (fast.val !== slow.val) return false
else fast = fast.next, slow = slow.next
} //i added these curly braces because the solution still works with them
return true
};
I was confused by the lack of curly braces so I added them to see if the loops were nested.
However, when I add curly braces to the second while loop, the code times out and if I add them to the first while loop, some test cases fail.
var isPalindrome = function(head) {
let slow = head, fast = head, prev, temp
while (fast && fast.next) {
slow = slow.next, fast = fast.next.next
prev = slow, slow = slow.next, prev.next = null
}
while (slow) {
temp = slow.next, slow.next = prev, prev = slow, slow = temp
fast = head, slow = prev;
}
while (slow) {
if (fast.val !== slow.val) return false
else fast = fast.next, slow = slow.next
}
return true
};
I also tried nesting the third while loop within the second like so,
var isPalindrome = function(head) {
let slow = head, fast = head, prev, temp
while (fast && fast.next) {
slow = slow.next, fast = fast.next.next
prev = slow, slow = slow.next, prev.next = null
}
while (slow) {
temp = slow.next, slow.next = prev, prev = slow, slow = temp
fast = head, slow = prev;
while (slow) {
if (fast.val !== slow.val) return false
else fast = fast.next, slow = slow.next
}
}
return true
};
and it still does not run. I have tried every variation of nesting possible with no luck, and I don't even know what to Google so I can understand.
what am I missing here? I am so confused
any help would be extremely appreciated. Thank y'all