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.
- 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
| Operation | Python list (Array) | Singly Linked List |
|---|---|---|
Random access i-th item | O(1) | O(n) (must walk from head) |
| Insert/delete at front | O(n) (shifts array) | O(1) (update head pointer) |
Insert/delete given node prev | O(n) | O(1) (prev.next = node.next) |
| Extra memory per item | 1 pointer | Value + 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)
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
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.
| Step | prev | curr | nxt saved | Pointer Flipped | Resulting Chain |
|---|---|---|---|---|---|
| Init | None | 1 | — | — | 1 -> 2 -> 3 -> None |
| 1 | None | 1 | 2 | 1.next = None | None <- 1, 2 -> 3 -> None |
| 2 | 1 | 2 | 3 | 2.next = 1 | None <- 1 <- 2, 3 -> None |
| 3 | 2 | 3 | None | 3.next = 2 | None <- 1 <- 2 <- 3 |
| End | 3 | None | — | Loop exits → return 3 | 3 -> 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, thentail = 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):
- Finding the Middle Node (
O(n)time,O(1)space): WhenfasthitsNone(even length) orfast.nextisNone(odd length),slowsits right at the middle! - Floyd's Cycle Detection (
O(n)time,O(1)space):- If the list has no cycle,
fastreachesNone. - If there IS a cycle,
fastenters the loop and closes the gap onslowby 1 node per turn, guaranteeingslow is fastbecomesTrueinstead of usingO(n)memory for avisitedset!
- If the list has no cycle,
Edge Cases to Always Guard Against
- Empty list (
head is None):while curr:andwhile fast and fast.next:exit safely, returningNone/False. - Single-node list (
1 -> None):reversereturns1;has_cycleseesfast.next is Noneand returnsFalse. - Self-cycle (
1 -> 1):fastandfast.nextare both1, soslowandfastboth advance to1andslow is fastreturnsTrueon step 1!
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!
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:
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
In has_cycle(head) using Floyd's Tortoise and Hare algorithm, what is the extra space complexity?
In reverse(head), why must you save nxt = curr.next BEFORE executing curr.next = prev?
Why should has_cycle check slow is fast instead of slow.val == fast.val?