In-place Reversal of a Linked List
Three pointers. Four lines. Zero extra memory. Reverse any portion of a linked list by redirecting .next pointers in a single pass.
Copy values to reverse — O(n) space. Redirect pointers in-place — O(1) space
The insight: you don't need to move data — you only need to flip pointers. Each node's .next is just a variable. Change it to point backward instead of forward. Three pointers track where you are, where you came from, and where you're going.
Two Reversal Types
Every in-place reversal problem is one of these two shapes.
Reverse the entire list. prev starts as None (new tail → None). When curr reaches None, prev is the new head. 4 lines in the loop body.
Reverse only nodes p to q. Three phases: walk to p-1, reverse q-p+1 nodes, stitch back. Save connection_before and last_node_of_sublist before starting.
The 3-Step Framework
The same 4-step inner loop works for every reversal — memorize it once.
prev represents the already-reversed portion (starts empty → None). curr is the node being processed. Always start both at the same end — prev=None, curr=head for full reversal.
prev = None curr = head
4 operations in order, every time: (1) save next_node = curr.next, (2) flip curr.next = prev, (3) advance prev = curr, (4) advance curr = next_node. Missing or reordering any step loses a pointer forever.
next_node = curr.next # 1. save curr.next = prev # 2. flip prev = curr # 3. advance prev curr = next_node # 4. advance curr
For sub-list reversal: before starting the reversal, save (1) last_node_of_first_part (node at p-1) and (2) last_node_of_sub_list (node at p, which becomes the tail). After reversing, reconnect both.
last_of_first = prev # node at p-1 last_of_sub = curr # node at p (becomes tail) # ... reverse ... last_of_first.next = prev # connect last_of_sub.next = curr # connect rest
Pattern Recognition
Spot the reversal pattern before the interviewer finishes the sentence.