Reverse Linked List – Solution & Complexity
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.
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.
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.
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).
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.