Step by step · Python and C++

Reverse a linked list, visualized step by step

Reversing a linked list in place (LeetCode 206) is four lines of code that almost everyone has to draw out on paper. Here the drawing is done for you, one pointer move at a time.

How it works
class Node:
    def __init__(self, val):
        self.val = val
        self.next = None

head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(4)

prev = None
curr = head
while curr is not None:
    nxt = curr.next
    curr.next = prev
    prev = curr
    curr = nxt

head = prev
print("reversed")

How linked list reversal works

Three pointers walk the list together. prev starts as null and curr at the head. On each iteration: save the next node so the rest of the list is not lost, point curr.next back at prev, then advance prev to curr and curr to the saved node. When curr becomes null, prev is the new head.

The Python example turns 1 → 2 → 3 → 4 into 4 → 3 → 2 → 1.

What to watch for when it runs

  1. Each iteration flips exactly one arrow.
  2. Between the flip and the advance the list is briefly in two pieces, and the saved next pointer is the only thing holding on to the second one.
  3. Delete the line that saves the next node and run it again to see the rest of the list become unreachable.

Time and space complexity

Time
O(n)
Space
O(1)

Every node is visited once and only three pointers are kept. The recursive version is just as fast but uses O(n) stack.

Stuck on your own version?

Paste it into the visualizer and watch your own code run, line by line — bugs included.