Linked List
A linked list gives you no indexing: you reach a node only by walking from the head.
Almost every problem is solved by moving a couple of pointers and rewiring next links,
usually in one pass and O(1) extra space.
When to reach for it
Section titled “When to reach for it”- The input is a singly linked list and you can’t just copy it into an array (or the problem asks for O(1) space).
- You need the middle, the n-th from the end, or to detect a cycle: use a fast and a slow pointer.
- You need to reverse all or part of the list: flip pointers in place.
- You build a new list from old nodes (merge, partition): use a dummy head so the first node is not a special case.
- The head itself might be removed or replaced: a dummy head fixes that too.
Template
Section titled “Template”dummy = ListNode(0, head) # 1. dummy head: the real head is never specialslow = fast = dummy # 2. two pointers, different speeds or a fixed gapwhile fast and fast.next: slow, fast = slow.next, fast.next.next
prev, cur = None, head # 3. in-place reversalwhile cur: cur.next, prev, cur = prev, cur, cur.nextreturn dummy.next # always return dummy.next, not headAlways ask: what if the list is empty, has one node, or the head is the node I change?
Save cur.next before you overwrite it, or you lose the rest of the list.
Problems in this guide
Section titled “Problems in this guide”- Reverse Linked List — flip each arrow while walking forward
- Merge Two Sorted Lists — dummy head, always take the smaller front node
- Linked List Cycle — fast and slow pointers meet inside a loop
- Remove Nth Node From End of List — keep a fixed gap between two pointers
- LRU Cache — hash map plus doubly linked list for O(1) everything