Reverse Linked List – Solution & Complexity
Watch: Reverse a Linked List with three pointers
Walk the list with prev, curr and next. At each node save next first, point curr back at prev, then move both pointers forward. When curr is None, prev is the new head: O(n) time, O(1) space. The recursive version works too but uses O(n) stack.
Solution Walkthrough
Step 1: Understand the Goal
- The input is a chain of nodes:
1 -> 2 -> 3 -> null. - Reversing it means every
nextpointer should point the other way:3 -> 2 -> 1 -> null. - The new head is the old tail, so the function must return the node that used to be last.
- The input is a chain of nodes:
Step 2: Track Three Pointers
- Walking the list forward while rewriting
nextpointers destroys the way back unless you keep a reference to what came before. - Keep three pointers as you walk:
prev(already-reversed portion),curr(node being processed), andnext_node(saved before you overwritecurr.next). - Start with
prev = Nonesince the new tail'snextmust benull.
- Walking the list forward while rewriting
Step 3: Rewire One Node at a Time
- Save
curr.nextbefore overwriting it, so you don't lose the rest of the list. - Point
curr.nextbackward atprev. - Advance both
prevandcurrone step forward for the next iteration.
- Save
Step 4: Confirm the Loop Termination and Complexity
- The loop stops when
currbecomesNone, meaning every original node has been rewired. - At that point
prevholds the new head (the old tail), which is exactly what the function returns. - Each node is visited once, so time complexity is O(n); only three pointers are kept, so space complexity is O(1).
- The loop stops when
Step 5: Alternative: Recursive Reversal
- Recursively reverse everything after the head first, then fix up the one link at the current level.
- Base case: an empty list or single node is already reversed.
- After the recursive call,
head.nextis the new tail, so sethead.next.next = headand detachhead.nextto avoid a two-node cycle. - This trades the O(1) space of the iterative version for O(n) call-stack space.