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
- prev=None, curr=1: save 2, point 1 → None, prev=1, curr=2
- save 3, point 2 → 1, prev=2, curr=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.
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
prev (reversed so far)
Solution · Python
def reverse_list(head):prev, curr = None, headwhile curr:nxt = curr.next # save the restcurr.next = prev # flipprev, curr = curr, nxtreturn prevStep 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
One small exercise per idea, right in the editor, before the problems below.
Practise it
Go further
Up next for you · Beginner
“Have I seen this?” is a set →