Skip to content
StackDecode
Linked listsAnimated

Reverse a Linked List

Flip each next pointer while walking the list.

Time

O(n)

Extra space

O(1)

Use it for

Fundamental pointer exercise.

How it works

  1. Use three pointers: prev (starts empty), curr (the node being processed) and next (saved so we do not lose the rest of the list).
  2. Save curr.next, then point curr.next backwards to prev.
  3. Move prev and curr one step forward.
  4. When curr runs off the end, prev is the new head. O(n) time, O(1) memory.

Watch it run

Loading animation…