prev
Head of the reversed prefix chain. Starts as null — because
before any processing, the reversed chain is empty. Ends as the new head of
the fully reversed list.
A line of train cars coupled nose-to-tail needs to reverse direction at a terminus.
A switch operator walks the chain, unhooking each car from the one ahead and
re-coupling it behind the growing reversed train. Three moving references —
prev, curr, and next — perform the same
rewiring on a linked list in a single pass: save the forward link, redirect the
current node backward, and advance. When the walk ends, prev holds
the new head. O(n) time. O(1) space.
At every moment during the traversal, the list is split into two chains:
a reversed prefix ending at prev, and an unreversed suffix
starting at curr. Each iteration moves one node from the
suffix into the prefix.
Head of the reversed prefix chain. Starts as null — because
before any processing, the reversed chain is empty. Ends as the new head of
the fully reversed list.
The node being processed right now. Its .Next pointer will
be redirected from the forward chain to the reversed chain. When curr
reaches null, every node has been rewired.
A temporary reference that saves curr.Next before we overwrite it.
Without this, rewiring curr.Next = prev would sever our only path
to the rest of the list.
The loop runs while curr ≠ null. Each iteration performs
exactly four pointer operations on the current node, then advances.
Store next = curr.Next. This preserves access to the
rest of the unreversed chain before we overwrite curr.Next.
Set curr.Next = prev. The current node now points backward
into the reversed prefix instead of forward into the unreversed suffix.
Set prev = curr. The reversed prefix has grown by one node —
prev now points to the node we just rewired.
Set curr = next. We move to the saved reference, resuming
the walk through the unreversed suffix.
The algorithm handles degenerate inputs gracefully — no special-case branches needed.
When head is null, curr starts as
null and the loop body never executes. prev remains
null, which is the correct answer: the reverse of an empty list
is an empty list.
With one node, the loop runs exactly once. next is saved as
null, curr.Next is set to null
(it already was), and prev becomes the sole node. The same
node is returned — a single-element list is its own reverse.
Try the "single node" preset.
The minimal non-trivial case. Two iterations swap the direction of the
single link. The original tail becomes the new head, and the original head
becomes the new tail with .Next = null.
Try the "two nodes" preset.