5.2 In-Place Linked List Reversal & Two-Pointer Patterns
π‘ Core Intuition: The 3-Second Mental Modelβ
π³ The Everyday Analogy: Uncoupling Train Cars & Two Paced Scoutsβ
Rather than laying down a parallel second railway track to reverse a train, walk between Car A and Car B, unhook the coupler, turn Car A backward onto a trailing bumper, and step onto Car B β repeating down the entire chain in place! And to locate the exact center of a blind tunnel in one pass without counting tiles first, send a fast runner (2x) alongside a steady walker (1x): the moment the fast runner taps the far exit wall, the walker stands right in the middle!
π» Bridging to Computer Science: Constant-Space Forward Pointer Masteryβ
Without array index arithmetic, forward pointer lists rely on two cornerstone time, space patterns:
- Sliding 3-Pointer Window (
prev, curr, next): Reverses directional pointers strictly in place. - Differential & Fixed-Gap Dual Pointers: Locates exact midpoints and -th tail offsets in a single sweep.
πTable of Contents
π In-Place Iterative Reversal: 3-Pointer Sliding Windowβ
Why do we need three pointers instead of two? The instant we flip curr->next = prev, node curr forgets which node originally followed it! Caching next = curr->next protects the suffix before inverting the pointer.
struct Node* reverseIterative(struct Node *head) {
struct Node *prev = NULL; // Trailing reversed head (alias r/q)
struct Node *curr = head; // Active node being inverted (alias p)
struct Node *next = NULL; // Lookahead node preserving suffix
while (curr != NULL) {
next = curr->next; // Step 1: Cache remaining list
curr->next = prev; // Step 2: Reverse forward link backward
prev = curr; // Step 3: Shift trailing boundary right
curr = next; // Step 4: Advance to cached node
}
return prev; // prev now points to the new HEAD
}
Recursive Reversal (Linear Call-Stack Unwind)β
Recursion pushes node pointers down the call stack, flipping links cleanly on unwind (head->next->next = head; head->next = NULL;). Omitting head->next = NULL creates a fatal 2-node infinite cycle at the former head!
π’π Two-Pointer Patterns: Middle Node & One-Pass k-th From Endβ
1. Fast & Slow Middle Finding (Odd vs. Even Termination)β
2. One-Pass k-th Node From End (Rigid Window)β
Advance first by nodes ahead of second, then walk both at velocity until first == NULL: second lands precisely on the -th tail node!
π Real-World Production Context: Merge Sort & In-Place Scannersβ
Production List Reversal & Two-Pointer Engines
Single-pass O(1) extra-space algorithms across sorting, palindromes, and memory-starved garbage collectors
Linked-List Merge Sort Splitting
O(n log n) Stable List Sort- Splits unsorted chains at the exact first midpoint in one O(n) fast/slow sweep.
- Merges sorted halves cleanly in O(1) extra heap space (unlike arrays needing O(n) buffers).
Deutsch-Schorr-Waite GC Traversal
Constant-Space Pointer Reversal- Reverses object pointers temporarily in-place during emergency garbage collection when stack space hits zero.
- Restores original graph topology cleanly during backtrack.
In-Place Palindrome & Tail Trim
Stream Verification- Combines fast/slow middle discovery + half-list reversal + element compare cleanly in O(1) RAM.
- Powers memory-locked streaming parsers.
π Numerical Applications & Worked Examplesβ
- Trace
prev,curr, andnextacross every loop iteration ofreverseIterative()onHEAD -> [10] -> [20] -> [30] -> NULL. - On even-length
[A -> B -> C -> D -> NULL], standardwhile (fast != NULL && fast->next != NULL)stops atC(second middle). Show how to adjust the loop condition so Merge Sort getsB(first middle) cleanly!
Step-by-Step Solution:β
-
Iterative 3-Pointer Trace:
- Init:
prev = NULL, curr = [10] - Iter 1:
next = [20];10->next = NULL;prev = [10], curr = [20] - Iter 2:
next = [30];20->next = [10];prev = [20], curr = [30] - Iter 3:
next = NULL;30->next = [20];prev = [30], curr = NULL - Returns
[30] -> [20] -> [10] -> NULL.
- Init:
-
Returning First Middle (
B) on Even Lists: Guardif (head == NULL) return NULL;, then loopwhile (fast->next != NULL && fast->next->next != NULL). Startingslow=A, fast=Asteps once toslow=B, fast=C, then terminates cleanly becausefast->next->next == NULL, returningB!
π― Exam & Interview Pitfall Checkβ
- Why is Iterative Reversal ( space) safer than Recursive Reversal ( space)?
- Reversing a 1-million-node linked list recursively pushes 1M stack frames ( immediate Stack Overflow crash!), whereas three local variables run smoothly on any length.
- How do you handle
k > listLengthsafely in the one-passk-th from end algorithm?- Check
if (first == NULL) return NULL;inside the initialk-step advance loop so you abort cleanly instead of crashing!
- Check
- Null-Guard Inversion (
fast->next != NULL && fast != NULL): Reversing the&&operand order dereferencesfast->nextwhenfast == NULLon even-length lists instant segfault! Always testfast != NULLfirst. - Omitting
head->next = NULLin Recursive Reversal: Leaves oldheadandhead->nextpointing directly at each other in a permanent 2-node infinite cycle! - Overwriting
curr->nextBefore Savingnext: Drops the entire trailing chain permanently in RAM!
π Navigation & Next Stepsβ
Next, we turn fast/slow runners onto cyclic topologies in Topic 5.3 β Floyd's Cycle Detection, Entry Proof & Loop Removal.
Never Study in Isolation. Join Binary Dose.
Connect with fellow engineers, clear conceptual doubts, and get 2 visual breakdowns & engineering mental models daily across our community channels.
Discord Community
Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.