206 · Reverse Linked List

Rewiring the chain, one pointer at a time.

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.


Interactive

Watch the pointers rewire the list


Concept

Three references, one invariant

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.

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.

initially null

curr

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.

moves forward each step

next

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 safety net

Algorithm

Four operations per node, one pass

The loop runs while curr ≠ null. Each iteration performs exactly four pointer operations on the current node, then advances.

  1. 1

    Save the forward link

    Store next = curr.Next. This preserves access to the rest of the unreversed chain before we overwrite curr.Next.

  2. 2

    Reverse the pointer

    Set curr.Next = prev. The current node now points backward into the reversed prefix instead of forward into the unreversed suffix.

  3. 3

    Advance prev

    Set prev = curr. The reversed prefix has grown by one node — prev now points to the node we just rewired.

  4. 4

    Advance curr

    Set curr = next. We move to the saved reference, resuming the walk through the unreversed suffix.


Edge Cases

When the list is trivial

The algorithm handles degenerate inputs gracefully — no special-case branches needed.

Empty list

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.

Single node

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.

Two nodes

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.