← Lessons

quiz vs the machine

Gold1340

Algorithms

In Place Reversal of a Linked List

Flip a chain of pointers using three references and no extra storage.

5 min read · core · beat Gold to climb

Rewiring the arrows

A linked list is a chain of nodes where each node points to the next. In place reversal flips every one of those pointers so the chain runs the other way, and it does so without allocating a second list. The pattern underlies many harder problems such as reversing a sublist or reversing nodes in groups.

The three pointer dance

Hold three references as you walk the list.

  • A previous pointer trails behind, starting empty.
  • A current pointer marks the node being rewired.
  • A next pointer saves where to go before you overwrite the link.

At each step you save the next node, point current backward to previous, then slide previous and current forward by one. When current runs off the end, previous is the new head.

Why save next first

The moment you redirect the current node to point backward, its forward link is gone. Capturing the next node beforehand is what keeps you from losing the rest of the list. This careful ordering is the whole trick.

Key idea

Reverse a list by walking it once with previous, current, and next references, always saving the next link before redirecting a node backward.

Check yourself

Answer to earn rating on the learn ladder.

1. Why must you save the next pointer before redirecting the current node?

2. After the loop ends, which reference is the new head?

3. How much extra memory does in place reversal use?