synopsis · Linear patterns · chapter 15
Linked Lists
10 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.
- what it is
A chain of nodes: each holds
valand anextreference, and the list is justhead. Splicing is O(1) once you're there; reaching the k-th node is O(k). - use it when
Inserts and deletes next to nodes you hold, LRU caches, hash chains — and every interview problem that hands you a
ListNode. - template
Dummy head:
ListNode dummy = new ListNode(0, head);walk withprev, thenreturn dummy.next;— no special case when the head changes. - template
Reverse:
next = curr.next; curr.next = prev; prev = curr; curr = next;then returnprev. Save before you flip. - template
Slow/fast:
while (fast != null && fast.next != null)→ middle (2nd), cycle (they meet), n-th from end (gap of n + 1). - cost
Index O(n) · splice O(1) once there · reverse / middle / cycle O(n) time, O(1) space · recursion over a list = O(n) stack.
- trap
Overwriting
curr.nextbefore saving it loses the rest of the list. Forgettingtail.next = nullafter splitting creates a cycle. - trap
Cycles need node identity (
==), not equal values. Andfast.next.nextneedsfast != null && fast.next != nullchecked first. - pro tip
Hard list problems are combos: Reorder = middle + reverse + merge · Palindrome = middle + reverse + compare · k-group = reverse a block, repeat.
- pro tip
O(1) get and put with recency → HashMap + doubly linked list (or
LinkedHashMapin access order).
Shaky on a card? Open the chapter or flip its recall cards.