Reversing a Linked List
Imagine your treasure-hunt chain: clue 1 → clue 2 → clue 3 → treasure. Now flip it: treasure → clue 3 → clue 2 → clue 1. Every arrow that pointed forward now points backward. The last node becomes the new head.
Reversing a linked list is one of the most fundamental linked-list operations, and it's a staple interview question because it tests whether you truly understand pointer manipulation. The good news: it's simpler than it looks.
The iterative approach
Walk through the list once, redirecting each pointer as you go. You need three variables:
prev— the previously processed node (starts asnull)curr— the node you're currently processing (starts athead)next— a temporary save ofcurr.nextbefore you overwrite it
At each step:
- Save
next = curr.next(so you don't lose the rest of the chain) - Flip the pointer:
curr.next = prev - Advance:
prev = curr,curr = next
When curr is null, you've processed every node. prev is now the new head.
← → arrow keys to step · click elements to interact
Reverse a Linked List (Iterative)
Walking through an example
List: 1 → 2 → 3 → 4 → null
Initial state: prev = null, curr = 1
- Step 1: save next=2, flip 1→null, advance. State: prev=1, curr=2
- Step 2: save next=3, flip 2→1, advance. State: prev=2, curr=3
- Step 3: save next=4, flip 3→2, advance. State: prev=3, curr=4
- Step 4: save next=null, flip 4→3, advance. State: prev=4, curr=null
curr is null — done. New head: 4 → 3 → 2 → 1 → null
The recursive approach
The recursive solution is more elegant to write but costs \(O(n)\) stack space — one stack frame per node:
The recursion goes all the way to the last node, then unwinds. On the way back up, each call makes its child point back at itself and sets its own forward pointer to null. The last node (base case) becomes the new head and is returned unchanged up through all the recursive calls.
Iterative vs. Recursive — which to choose?
- Iterative: \(O(1)\) space — preferred in production and for very long lists (no stack overflow risk)
- Recursive: \(O(n)\) stack space — cleaner to read and reason about, but risky for lists with millions of nodes
Both run in \(O(n)\) time. In interviews, demonstrating both and explaining the tradeoff is the ideal answer.
Variations
The same pointer-manipulation logic powers more complex operations:
- Reverse a sublist — reverse only nodes from position m to n
- Reverse in k-groups — reverse every k nodes in chunks
- Palindrome check — reverse the second half and compare to the first