IntermediateLinked List

Reversing a linked list without losing it

Three : prev, curr, next. Save next first, flip curr.next to prev, then step forward. Save before you flip.

The idea

Reversing means pointing every back at the one before it. The danger: once you change curr.next you've lost the rest of the list, so save it first.

A before the head is a related trick: it removes the special case when the head itself changes, in merging or removing nodes.

Worked example

1 → 2 → 3

  1. prev=None, curr=1: save 2, point 1 → None, prev=1, curr=2
  2. save 3, point 2 → 1, prev=2, curr=3
  3. save None, point 3 → 2, prev=3, curr=None → new head is 3: 3 → 2 → 1

Pseudocode

The steps in plain words. ← means “set to”; indentation shows what's inside what.

prev ← None, current ← head
while current isn't None:
next ← current.next(save the rest)
current.next ← prev(flip the arrow)
prev ← current
current ← next
return prev(the old tail is the new head)

See it run

The worked example, step by step, beside the Python. The highlighted line is the one running.

Step-by-step

1 → 2 → 3

1
▲ current
→
2
→
3
→ null

prev (reversed so far)

null

Solution · Python

def reverse_list(head):
prev, curr = None, head
while curr:
nxt = curr.next # save the rest
curr.next = prev # flip
prev, curr = curr, nxt
return prev

Step 1 of 8

Walk the list once, flipping each arrow to point back. PREV is the part already reversed; CURRENT is the node being flipped.

time, space.

How to spot it

  • Reversing all or part of a list, lists, reorder list.

Common mistakes

  • Flipping before saving next.
  • Returning head (now the tail) instead of prev.

Practise the ideas first

Practise it

Go further