Skip to main content

5.2 In-Place Linked List Reversal & Two-Pointer Patterns

πŸ“šModule 05 β€’ Linked ListsTopic 5.2⏱️15 min read
🎯High-Yield For:Semester Exams β€’ Technical Interviews β€’ Engineering Foundations

πŸ’‘ 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 O(1)\mathcal{O}(1) array index arithmetic, forward pointer lists rely on two cornerstone O(n)\mathcal{O}(n) time, O(1)\mathcal{O}(1) space patterns:

  1. Sliding 3-Pointer Window (prev, curr, next): Reverses directional pointers strictly in place.
  2. Differential & Fixed-Gap Dual Pointers: Locates exact midpoints and kk-th tail offsets in a single sweep.

πŸ” 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 kk nodes ahead of second, then walk both at 1Γ—1\times velocity until first == NULL: second lands precisely on the kk-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​

πŸ“Problem Statement: Iterative Reversal Trace & Merge Sort First-Middle Modificationtheorem
  1. Trace prev, curr, and next across every loop iteration of reverseIterative() on HEAD -> [10] -> [20] -> [30] -> NULL.
  2. On even-length [A -> B -> C -> D -> NULL], standard while (fast != NULL && fast->next != NULL) stops at C (second middle). Show how to adjust the loop condition so Merge Sort gets B (first middle) cleanly!

Step-by-Step Solution:​

  1. 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.
  2. Returning First Middle (B) on Even Lists: Guard if (head == NULL) return NULL;, then loop while (fast->next != NULL && fast->next->next != NULL). Starting slow=A, fast=A steps once to slow=B, fast=C, then terminates cleanly because fast->next->next == NULL, returning B!


🎯 Exam & Interview Pitfall Check​

Core Conceptual Questions
  1. Why is Iterative Reversal (O(1)\mathcal{O}(1) space) safer than Recursive Reversal (O(n)\mathcal{O}(n) space)?
    • Reversing a 1-million-node linked list recursively pushes 1M stack frames (β€…β€ŠβŸΉβ€…β€Š\implies immediate Stack Overflow crash!), whereas three local variables run smoothly on any length.
  2. How do you handle k > listLength safely in the one-pass k-th from end algorithm?
    • Check if (first == NULL) return NULL; inside the initial k-step advance loop so you abort cleanly instead of crashing!
Common Interview Traps: Architectural Trade-Offs
  • Null-Guard Inversion (fast->next != NULL && fast != NULL): Reversing the && operand order dereferences fast->next when fast == NULL on even-length lists β€…β€ŠβŸΉβ€…β€Š\implies instant segfault! Always test fast != NULL first.
  • Omitting head->next = NULL in Recursive Reversal: Leaves old head and head->next pointing directly at each other in a permanent 2-node infinite cycle!
  • Overwriting curr->next Before Saving next: 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.

πŸš€ Level Up Your Engineering Mindset

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
Official Hub

Discord Community

Start at #welcome-and-rules, say hello in #general-chat, clear doubts, and collaborate with engineers worldwide.

Join Discord Server→
⚑
Daily Knowledge Drops

Daily Visual Deep-Dives

Bite-sized system design schematics, core OS internals, and DSA intuition served right into your feeds every single day.

πŸ’‘Help keep Binary Dose free for students, or share your articles and notes.