Linked Lists
🧠 Spot It
Use Linked List patterns when:
- Problem involves pointer manipulation (reversal, merging, cycle)
- O(1) space constraint — no converting to array
- Relative ordering of nodes matters
Pattern 1 — Fast & Slow Pointers (Floyd's)
Detect cycles, find midpoint, find kth from end.
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
def find_middle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow # slow is at middle
Pattern 2 — In-Place Reversal
def reverse_list(head):
prev, curr = None, head
while curr:
next_node = curr.next
curr.next = prev
prev = curr
curr = next_node
return prev
Pattern 3 — Merge Two Sorted Lists
def merge_two_lists(l1, l2):
dummy = ListNode(0)
curr = dummy
while l1 and l2:
if l1.val <= l2.val:
curr.next = l1
l1 = l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
curr.next = l1 or l2
return dummy.next
Senior Tricks
- Dummy node — always use
dummy = ListNode(0); dummy.next = headto avoid edge cases on head removal - Two-pass trick — first pass to get length, second pass to find target position
- Draw it out — pointer problems are visual; sketch before coding
Problems
| # | Problem | Pattern | Link | Status |
|---|---|---|---|---|
| 1 | Reverse Linked List | In-place Reversal | LC 206 | |
| 2 | Merge Two Sorted Lists | Merge | LC 21 | |
| 3 | Linked List Cycle | Fast & Slow | LC 141 | |
| 4 | Middle of the Linked List | Fast & Slow | LC 876 | |
| 5 | Reorder List | Reverse + Merge | LC 143 | |
| 6 | Remove Nth Node From End | Two-pass | LC 19 | |
| 7 | Merge K Sorted Lists | Heap + Merge | LC 23 |