Reverse a linked list, one frame at a time

Nothing is rewired on the way down.

Five frames pile up without changing a single pointer. Then, on the way back up, each frame flips exactly one link.

The list and its pointers at the current step
original reversed just changed not yet written

Five nodes, each pointing at the next. Press Next to make the first call.

Call stack

    reverseList

    What the stepper shows

    The leap of faith, precisely

    At the moment prev = reverseList(head->next) returns in the frame for node 3, nodes 4 and 5 are already reversed and node 4 is now the tail of that reversed part. Nobody touched node 3's next, so it still points straight at node 4.

    You never verify the assumption. You grant it, then do one honest step of work with what it handed you.

    Why the base case has two halves

    See it in your own debugger

    Put a breakpoint on head->next->next = head;, run with F5, and press Continue four times. head->val arrives as 4, then 3, 2, 1 — innermost first, exactly as above.

    Cost: O(n) time, one pass. O(n) space, because all n frames are open at the deepest point. The iterative three-pointer version is the O(1)-space answer.