Reverse a linked list

Lesson 9.2 · Easy · Pointer rewiring · 6 min · by Vinay C

We'll cover the following

Reverse a singly linked list in place.

Watch it run

Press Play or Step to walk through the example, or change the input and press Run. Each frame says what the algorithm does and why.

12 items · 13 steps
cur30
next81
12
93
44
75
26
67
58
109
1210
1111

Save next (8). Point 3 back at null. Move prev and cur forward.

reversed part: null

1 / 13

The idea

Complexity

TimeSpaceWhy
O(n)O(1)Each arrow is flipped once, in place.

In Python

def reverse(head):
    prev = None
    while head:
        nxt = head.next        # remember the rest
        head.next = prev       # flip the arrow
        prev, head = head, nxt # step forward
    return prev

Summary: say it in the interview

  • Walk the list with three names: prev, cur and next. Save next, flip cur to point back at prev, then slide all three forward. Nothing is copied, so memory stays constant.
  • Time O(n), space O(1). Each arrow is flipped once, in place.