Data Structures and Algorithms5 min read

Linked-List Tricks: Dummy Heads, Fast-Slow Pointers, and In-Place Reversal

Why sentinel dummy heads remove head-pointer corner cases, how Floyd's tortoise-and-hare proof finds midpoints and cycle entry nodes, and how to rewire sublists cleanly in O(1) space.

Three pointer techniques handle almost every linked-list interview problem in O(1) extra space: attaching a dummy sentinel before head to unify edge mutations, running fast-and-slow pointers to locate midpoints or cycle entry nodes, and saving nxt before rewiring curr.next backward during in-place reversal.

Key takeaways

  • Treat dummy.next as the single authoritative head return value whenever list topology changes.
  • Remember the two-phase distance proof behind Floyd's cycle entry reset rather than memorizing code blindly.
  • Draw pointer assignments in exact evaluation order so you never lose the remainder of the list.

Quick facts

  • A dummy sentinel node eliminates separate null checks when deleting, inserting, or reversing at index zero.
  • Advancing slow by 1 step and fast by 2 steps locates the middle node in a single pass.
  • Floyd's cycle detection guarantees O(n) time and O(1) auxiliary space without a visited set.
  • Using while fast and fast.next: avoids AttributeError when dereferencing fast.next.next.

Why Linked Lists Trip Strong Engineers

Linked-list questions are less about algorithmic cleverness and more about pointer discipline under pressure. As summarized in the NeetCode roadmap breakdown, linked lists train you to manipulate references in place without allocating an O(n)O(n) array copy.

Almost every bug candidates hit comes from losing a reference before reading .next, treating the first node differently from interior nodes, or indexing past None. Three small habits remove almost all of that friction.

Sentinel dummy head, three-pointer in-place reversal, and fast-slow cycle geometry
Sentinel dummy head, three-pointer in-place reversal, and fast-slow cycle geometry

Diagram: Original vector diagram by Ajay Kumar Chaturvedi (CC BY 4.0).

Intuition Behind the Three Core Tricks

1. Sentinel dummy nodes erase head special cases

Whenever an operation might remove, replace, or reorder the original head, create dummy = ListNode(0, head) and track a lagging cursor prev = dummy. Because head now sits behind a real node, deleting node 0 uses the exact same prev.next = prev.next.next logic as deleting node 5, and you simply return dummy.next.

This same sentinel pattern cleans up merging two sorted lists and removing the $n$-th node from the end: keep a tail pointer starting at dummy, append whichever node holds the smaller value, and attach the remaining non-empty chain afterward. For nn-th from the end, advance a lead pointer n steps ahead from dummy, then move lead and lag together until lead.next is None; lag lands squarely on the predecessor of the node to delete, even when deleting the first element.

2. Fast-and-slow pointers and Floyd's cycle geometry

Moving slow by one step and fast by two steps solves two classic problems in one pass without storing nodes in a set:

  1. Middle split: When fast reaches the end (not fast or not fast.next), slow rests at the midpoint. Initializing fast = head stops slow on the second middle for even lengths ([1, 2, 3, 4] gives 3), whereas fast = head.next stops slow on the first middle (2), which is critical when cutting a list into two non-overlapping halves (mid.next = None) for merge sort or palindrome verification.
  2. Cycle entry: As formalized in the Wikipedia cycle detection analysis, let aa be the steps from head to cycle entry EE, bb be steps from EE to meeting node MM, and LL be cycle length. At collision, fast traveled 2(a+b)2(a + b) steps while slow traveled a+ba + b, so a+ba + b is a multiple of LL. Thus walking aa more steps from MM reaches EE again. Resetting one pointer to head and stepping both by 1 brings them together at EE.

When linked-list questions escalate into system-design classics like LRU Cache, pair a sentinel-bounded doubly linked list (head_sentinel and tail_sentinel) with a hash map from key to node reference so moving an accessed item to the front and evicting the oldest tail both run in O(1)O(1) without scanning.

Full reversal swaps three variables per node: save nxt = curr.next, flip curr.next = prev, advance prev = curr, and step curr = nxt. Sublist reversal (reverse_between) gets even cleaner with head-insertion: anchor pre right before the segment and tail on its first node, then pull each nxt = tail.next straight behind pre.

Four-step trace of reversing sublist nodes 2, 3, 4 in place
Four-step trace of reversing sublist nodes 2, 3, 4 in place

Diagram: Original vector diagram by Ajay Kumar Chaturvedi (CC BY 4.0).

Working Python Code

Here is a self-contained module implementing ListNode, in-place reversal (reverse_list), sublist reversal (reverse_between), and Floyd's cycle entry detector (detect_cycle), verified with test lists.

PYTHON
from __future__ import annotations


class ListNode:
    def __init__(self, val: int = 0, next_node: ListNode | None = None) -> None:
        self.val = val
        self.next = next_node


def build_list(values: list[int]) -> ListNode | None:
    dummy = ListNode()
    tail = dummy
    for v in values:
        tail.next = ListNode(v)
        tail = tail.next
    return dummy.next


def to_list(head: ListNode | None) -> list[int]:
    out: list[int] = []
    curr = head
    while curr is not None:
        out.append(curr.val)
        curr = curr.next
    return out


def reverse_list(head: ListNode | None) -> ListNode | None:
    prev: ListNode | None = None
    curr = head
    while curr is not None:
        nxt = curr.next
        curr.next = prev
        prev = curr
        curr = nxt
    return prev


def reverse_between(head: ListNode | None, left: int, right: int) -> ListNode | None:
    if head is None or left == right:
        return head
    dummy = ListNode(0, head)
    pre = dummy
    for _ in range(left - 1):
        assert pre.next is not None
        pre = pre.next
    tail = pre.next
    assert tail is not None
    for _ in range(right - left):
        nxt = tail.next
        assert nxt is not None
        tail.next = nxt.next
        nxt.next = pre.next
        pre.next = nxt
    return dummy.next


def detect_cycle(head: ListNode | None) -> ListNode | None:
    slow = head
    fast = head
    while fast is not None and fast.next is not None:
        assert slow is not None
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            entry = head
            while entry is not slow:
                assert entry is not None and slow is not None
                entry = entry.next
                slow = slow.next
            return entry
    return None


if __name__ == "__main__":
    assert to_list(reverse_list(build_list([1, 2, 3, 4]))) == [4, 3, 2, 1]
    assert to_list(reverse_between(build_list([1, 2, 3, 4, 5]), 2, 4)) == [1, 4, 3, 2, 5]
    nodes = [ListNode(i) for i in range(4)]
    for idx in range(3):
        nodes[idx].next = nodes[idx + 1]
    nodes[3].next = nodes[1]
    assert detect_cycle(nodes[0]) is nodes[1]
    print("reverse_between:", to_list(reverse_between(build_list([1, 2, 3, 4, 5]), 2, 4)))
    entry = detect_cycle(nodes[0])
    print("cycle entry val:", entry.val if entry else None)

Running this script produces:

TEXT
reverse_between: [1, 4, 3, 2, 5]
cycle entry val: 1

Complexity Analysis

Trick / AlgorithmTime ComplexityExtra SpaceNotes
Dummy-head deletion / mergeO(n)O(n)O(1)O(1)Sentinel removes separate head branch
Three-pointer in-place reversalO(n)O(n)O(1)O(1)Fixed number of pointer updates per node
Floyd's cycle detectionO(n)O(n)O(1)O(1)At most a+La + L steps after entering cycle

Comparing Blind 75 against NeetCode 150, linked-list questions stay compact in both tracks precisely because interviews test pointer hygiene over heavy theory. Recursive reversal is clean to write, yet it consumes O(n)O(n) call-stack frames and risks hitting Python's default recursion limit on long chains, so I always code the iterative pointer loop in interviews.

Common Mistakes and When I Skip In-Place Rewiring

Watch out for these recurring errors:

  • Returning `head` instead of `dummy.next`: After modifying node 0 (such as reversing from position 1 or removing the first element), head still points to the old first node, which might now sit mid-list or unlinked.
  • Checking only `while fast:`: Calling fast.next.next when fast.next is None crashes on odd-length acyclic lists.
  • Comparing node values instead of identity (`is`): In cycle detection, duplicate .val integers exist in distinct nodes; always test slow is fast, never slow.val == fast.val.
  • Creating self-loops during reversal: Writing nxt.next = pre.next before tail.next = nxt.next when reversing sublists corrupts the chain if tail and nxt are adjacent.

I skip O(1)O(1)-space in-place mutation whenever a question forbids mutating input nodes (for example, concurrent readers or persistent immutable structures), or when an interviewer specifically permits copying values into a hash table for rapid prototyping before tightening space.

Practice Problems

Apply these pointer tricks across two foundational prompts:

  1. Reverse Linked List: Write the iterative three-pointer loop cleanly and trace the final state when the input has zero or one node.
  2. Linked List Cycle II: Implement Floyd's two-phase cycle entry algorithm without using a set and verify both a == 0 (cycle starts at head) and acyclic lists.

Sources