How do you reverse a singly linked list?
Walk through the list once with three pointers (previous, current and next) and turn each arrow around so it points backwards. The last node you visit becomes the new head. O(n) time, O(1) extra space.
Explain it simply
A linked list is like a line of people where each person points at the next one. To reverse it, you walk down the line and ask each person to point at the person behind them instead. You need to remember three people at every step: the one behind you (prev), the one you are talking to (current) and the one ahead (next), so you do not lose the rest of the line when the arrow is turned around.
Line by line
function reverseList(head) {
let prev = null; // nothing is behind the first node yet
let current = head;
while (current !== null) {
const next = current.next; // 1. remember the rest of the list
current.next = prev; // 2. turn this node's arrow around
prev = current; // 3. move prev forward
current = next; // 4. move current forward
}
return prev; // prev is the old last node, now the head
}
// Build 1 -> 2 -> 3
const list = { val: 1, next: { val: 2, next: { val: 3, next: null } } };
let node = reverseList(list);
const values = [];
while (node) {
values.push(node.val);
node = node.next;
}
console.log(values.join(" -> ")); // Output: 3 -> 2 -> 1- Step 1 must happen before step 2; otherwise you lose the pointer to the remaining nodes.
- When the loop ends,
currentisnullandprevpoints at the new first node.
Approaches
- Iterative with three pointers (above): the standard answer.
- Recursive: reverse the rest of the list, then make the next node point back to the current one. Elegant, but it uses the call stack.
- Copy into an array and rebuild: easy to write but wastes O(n) memory, so interviewers usually want one of the first two.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| Iterative | O(n) | O(1) |
| Recursive | O(n) | O(n) call stack |
Common mistakes
- Overwriting
current.nextbefore saving it. - Returning
headat the end (that is now the last node). - Not handling an empty list or a single node; the loop above handles both.
What to say in the interview
"I would reverse it iteratively with three pointers. For each node I save its next pointer, point it back to the previous node, and then move both pointers forward. When current becomes null, prev is the new head. That runs in O(n) time and O(1) extra space. I would also mention the recursive version, which is shorter but uses O(n) stack space."
Follow-up questions
- How would you reverse only the nodes between positions m and n?
- How do you reverse a list in groups of k?
- How can you check whether a linked list is a palindrome?