Reversing In Place
The three-pointer reversal, traced step by step, plus reversing just a slice of the list.
12 min, 0 of 3 activities solved
View cheatsheetGetting Python ready… examples can run in a moment.
Reversal is the linked list move. It shows up on its own and as a step inside bigger problems (palindromes, reordering, k-groups, adding numbers).
The idea: walk the list once and flip each arrow to point backwards. You need three pointers:
prev: the already-reversed part (startsNone)cur: the node being flippednxt: a bookmark to the rest, saved before you overwritecur.next
before: None 1 -> 2 -> 3 -> None
prev cur
step 1: None <- 1 2 -> 3 -> None
prev cur
step 2: None <- 1 <- 2 3 -> None
prev cur
When cur falls off the end, prev is the new
head. O(n) time, O(1) extra space: no new nodes.
Three pointers, traced
Watch the two halves: the reversed part grows at its front while the rest shrinks. Try swapping lines 1 and 2 to see how losing the bookmark cuts the list.
The loop runs only twice. What does this print?
The recursive version
Elegant, but it uses O(n) call-stack space and Python stops at ~1,000 nested calls. In interviews (and in the practice problems with big inputs) prefer the iterative loop.
Variation: reverse just a slice. To reverse
positions left..right (1-indexed):
- Put a dummy before the head and walk to
before, the node just ahead of the slice. - Run the same three-pointer loop exactly
right - left + 1times starting atbefore.next. - Reconnect: the slice's old first node is now its
last, so point it at
cur(the node after the slice), and pointbefore.nextatprev.
1 -> [2 -> 3 -> 4] -> 5 left=2, right=4
1 -> [4 -> 3 -> 2] -> 5
Same loop, plus careful stitching. The k-group problem at the end of this unit repeats this for every block of k nodes.
Why does the slice reversal start from a dummy node placed before the head?
So before exists even when left = 1 (the slice starts at the head)
Reverse a sublist
Write reverse_between(head, left, right) that
reverses the nodes at positions left through
right (1-indexed, left <= right) and returns
the head of the whole list.
[1, 2, 3, 4, 5], left 2, right 4 gives
[1, 4, 3, 2, 5].
Rewire the existing nodes in one pass.