Palindrome linked list
Easy TimeO(n) SpaceO(n)
Given the head of a singly linked list, return true when its values read the same forwards and backwards — [1, 2, 3, 2, 1] does. The list can only be traversed forwards, comparison is by value rather than by node, and an empty list or a single node is a palindrome.
Examples
Example 1
- Input
- head = buildList([1, 2, 3, 2, 1])
- Output
true1and1,2and2, with the3alone in the middle.
Example 2
- Input
- head = buildList([1, 2])
- Output
false1and2are different values, so it does not read the same backwards.
The Code
function buildList(values) {
let head = null;
for (let i = values.length - 1; i >= 0; i--) {
head = { val: values[i], next: head };
}
return head;
}
function isPalindrome(head) {
const values = [];
let node = head;
while (node) {
values.push(node.val);
node = node.next;
}
let left = 0;
let right = values.length - 1;
while (left < right) {
if (values[left] !== values[right]) return false;
left++;
right--;
}
return true;
}
isPalindrome(buildList([1, 2, 3, 2, 1]));Done
The first 9 calls, of 17. This one does not fit on a page.
More like this
All linked lists examples (9) →- Reverse a list Three pointers, one pass — flip every link as you walk.
- Detect a cycle A slow and a fast pointer must meet if the list loops.
- Middle node When the fast pointer finishes, the slow one is halfway.
- Merge two lists A dummy head removes every special case for the first node.
- Remove nth from end Open an n-node gap between two pointers, then walk them together.
- Merge k lists Merge lists in pairs, halving how many remain each round.