Reverse a linked list
Easy TimeO(n) SpaceO(1)
A singly linked list only points forwards: there is no index into it and no way back. Given the head of one, reverse it and return the new head, so [1, 2, 3, 4, 5] becomes [5, 4, 3, 2, 1]. Each node holds a value and a single pointer, and the reversal has to come from re-pointing the existing nodes rather than from building a new list. An empty list and a one-node list are already reversed.
Examples
Example 1
- Input
- node = reverseList(buildList([1, 2, 3, 4, 5]))
- Output
- Five nodes, each now pointing at the one that used to point at it.
[5,4,3,2,1]
Example 2
- Input
- node = reverseList(buildList([7]))
- Output
- One node points at nothing in either direction, so it is already its own reverse.
[7]
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 toArray(node) {
const out = [];
while (node) {
out.push(node.val);
node = node.next;
}
return out;
}
function reverseList(head) {
let prev = null;
let current = head;
while (current) {
const nextNode = current.next;
current.next = prev;
prev = current;
current = nextNode;
}
return prev;
}
toArray(reverseList(buildList([1, 2, 3, 4, 5])));Done
The first 9 calls, of 21. This one does not fit on a page.
More like this
All linked lists examples (9) →- 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.
- Palindrome list A list can’t be read backwards — so copy it out, then close in.
- Merge k lists Merge lists in pairs, halving how many remain each round.