Linked List

Linked List

Nodes linked by pointers. No index access — must traverse. Master reversal, cycle detection, and dummy nodes.

Reverse a Linked List — Step by Step
prev curr nxt (saved)
Press Animate to see reversal step by step.

Reversal — The 3-Pointer Dance

Save nxt = curr.next (don't lose the chain!)
Flip the pointer: curr.next = prev
Advance: prev = curr, curr = nxt
Must save nxt FIRST
If you do curr.next = prev before saving curr.next, you lose the rest of the list forever.
Fast & Slow Pointer — Find Middle
slow (moves 1) fast (moves 2)
Fast moves 2x speed. When fast reaches end, slow is at middle.

Cycle Detection — Floyd's Algorithm

Why it works
If there's a cycle, fast will lap slow inside it. Like two runners on a circular track — the faster one always catches up. If no cycle, fast reaches null first.
def has_cycle(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow == fast: return True
    return False
Check both fast AND fast.next
Checking only fast will crash when fast.next.next is accessed on a node with null next.

Node + Reversal + Dummy Node

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val; self.next = next

# Reverse — O(n), O(1) space
def reverse_list(head):
    prev, curr = None, head
    while curr:
        nxt = curr.next    # 1. save next
        curr.next = prev   # 2. flip pointer
        prev = curr        # 3. advance prev
        curr = nxt         # 4. advance curr
    return prev            # prev = new head

# Dummy node trick — head might change
dummy = ListNode(0)
dummy.next = head
curr = dummy
# ... do operations ...
return dummy.next  # new head

Fast & Slow Patterns

# Find middle of linked list
slow = fast = head
while fast and fast.next:
    slow = slow.next
    fast = fast.next.next
# slow = middle node

# Kth from end — move fast k steps first
def kth_from_end(head, k):
    fast = slow = head
    for _ in range(k): fast = fast.next
    while fast:
        slow = slow.next
        fast = fast.next
    return slow

LeetCode Problems

  • EasyReverse Linked List3-pointer iterative
  • EasyLinked List CycleFast & slow pointers
  • EasyMiddle of Linked ListFast & slow pointers
  • MediumRemove Nth Node From EndFast k steps ahead + dummy
  • MediumMerge Two Sorted ListsDummy node + pointer
  • MediumReorder ListFind mid + reverse + merge
  • HardMerge K Sorted ListsHeap of (val, node)