4. Linked Lists, Trees & Heaps

Singly Linked Lists, Reversal & Fast/Slow Pointers

Master pointer manipulation in Python: build Node classes, reverse a linked list in O(1) space, use dummy sentinel nodes, and detect cycles with Floyd's fast/slow pointers.

6 min readUpdated 2026-11-30
In This Lesson
  • Implement a singly linked list Node and reverse pointers cleanly in O(n) time, O(1) space
  • Simplify head-insertion and merging edge cases using a dummy sentinel node
  • Find middle nodes and detect cycles in O(1) space using fast/slow pointers

Arrays store items side-by-side in one contiguous memory block; Linked Lists store Node(val, next) objects scattered in memory chained together by references. Two essential patterns solve almost every linked-list interview question: dummy sentinel nodes and fast/slow pointers.

Why It Matters: Arrays vs Linked Lists

OperationPython list (Array)Singly Linked List
Random access i-th itemO(1)O(n) (must walk from head)
Insert/delete at frontO(n) (shifts array)O(1) (update head pointer)
Insert/delete given node prevO(n)O(1) (prev.next = node.next)
Extra memory per item1 pointerValue + next pointer object

Whenever you modify pointers in-place, the golden rule is: save the next reference before overwriting a .next link, and never lose track of your head!

Pattern 1: In-Place Reversal (prev, curr, nxt)

python
from typing import Optional

class ListNode:
    def __init__(self, val: int = 0, next: Optional["ListNode"] = None):
        self.val = val
        self.next = next

def reverse_list(head: Optional[ListNode]) -> Optional[ListNode]:
    prev, curr = None, head
    while curr:
        nxt = curr.next     # 1. Save remainder of list BEFORE breaking link!
        curr.next = prev    # 2. Flip arrow backward
        prev = curr         # 3. Advance prev
        curr = nxt          # 4. Advance curr
    return prev             # prev sits on the new head!

Step-by-Step Dry-Run Trace: 1 -> 2 -> 3 -> None

Interactive Walkthrough: Reversing a Linked List in O(1) SpaceStep 1 / 4
prev = Nonecurr = 1nxt = 2
None ← prev1 → 2 → 3 → None

Init: prev=None, curr=1

Before flipping any pointer, save nxt = curr.next (node 2) so we don't lose the rest of the list.

Stepprevcurrnxt savedPointer FlippedResulting Chain
InitNone1——1 -> 2 -> 3 -> None
1None121.next = NoneNone <- 1, 2 -> 3 -> None
21232.next = 1None <- 1 <- 2, 3 -> None
323None3.next = 2None <- 1 <- 2 <- 3
End3None—Loop exits → return 33 -> 2 -> 1 -> None

Pattern 2: Dummy Sentinel Nodes (Zero Head Edge Cases)

Building or merging linked lists gets messy when you need special if head is None: checks for the very first node. Creating dummy = Node(0) and tail = dummy gives you a guaranteed non-None anchor:

  • Append new nodes via tail.next = node, then tail = tail.next.
  • At the end, simply return dummy.next!

Pattern 3: Fast & Slow Pointers (Middle Node & Cycle Detection)

Move slow by 1 step and fast by 2 steps (slow = slow.next, fast = fast.next.next):

  1. Finding the Middle Node (O(n) time, O(1) space): When fast hits None (even length) or fast.next is None (odd length), slow sits right at the middle!
  2. Floyd's Cycle Detection (O(n) time, O(1) space):
    • If the list has no cycle, fast reaches None.
    • If there IS a cycle, fast enters the loop and closes the gap on slow by 1 node per turn, guaranteeing slow is fast becomes True instead of using O(n) memory for a visited set!

Edge Cases to Always Guard Against

  • Empty list (head is None): while curr: and while fast and fast.next: exit safely, returning None / False.
  • Single-node list (1 -> None): reverse returns 1; has_cycle sees fast.next is None and returns False.
  • Self-cycle (1 -> 1): fast and fast.next are both 1, so slow and fast both advance to 1 and slow is fast returns True on step 1!
Forgetting `while fast and fast.next:` in Fast/Slow Pointers

Writing while fast.next: crashes with AttributeError: 'NoneType' object has no attribute 'next' when fast lands on None (for example, on an empty list or an even-length list). Always check both fast and fast.next!

Use `slow is fast` (Identity), Not `slow.val == fast.val`

Two distinct nodes in a linked list can hold the same integer value (like 2 -> 5 -> 2). Always compare node object identity (slow is fast) when detecting cycles, never .val!

Try It Yourself in the Playground

Test reverse, merge_two_sorted (with a dummy sentinel), middle_node, and has_cycle right below:

Python 3Try It Live: Linked List Reversal, Dummy Merge & Cycle Detection
Output

Click “Run Code” to execute this snippet right in your browser.

Mini-Challenge: Why is creating a dummy = Node(0) helpful when building or merging linked lists?

Quick Checkpoints

Check Your Understanding

In has_cycle(head) using Floyd's Tortoise and Hare algorithm, what is the extra space complexity?

Check Your Understanding

In reverse(head), why must you save nxt = curr.next BEFORE executing curr.next = prev?

Check Your Understanding

Why should has_cycle check slow is fast instead of slow.val == fast.val?