Palindrome Linked List
Given a singly linked list, determine if it is a palindrome.
Example: head = [1,2,2,1] → true
Sample Input
—
Sample Output
—
Constraints
- 1 to 10^5 nodes
- 0 <= Node.val <= 9
Topics
Reverse Second Half
function isPalindrome(head) {
let slow = head, fast = head;
while (fast && fast.next) { slow = slow.next; fast = fast.next.next; }
let prev = null;
while (slow) { const next = slow.next; slow.next = prev; prev = slow; slow = next; }
while (prev) {
if (prev.val !== head.val) return false;
prev = prev.next; head = head.next;
}
return true;
}
Time: O(n) | Space: O(1)
Saved in this browser only. Private to you.