Linked Lists
Signal: the input is a ListNode chain; reversing, merging, reordering, detecting cycles, finding the middle or the k-th from the end; or O(1) insert/delete in the middle (LRU caches).
Core idea: linked-list problems are pointer surgery. Three tools cover almost everything:
- Dummy (sentinel) head. Removes special cases when the head itself may change.
- Iterative reversal with
prev,curr,next. - Fast & slow pointers. Fast moves 2 steps and slow moves 1. They find the middle, detect cycles, and find the k-th node from the end (with a k-step head start).
python
class ListNode:
def __init__(self, val=0, next=None):
self.val, self.next = val, next
# Reverse in place
prev, curr = None, head
while curr:
nxt = curr.next # 1. save
curr.next = prev # 2. reverse the pointer
prev, curr = curr, nxt # 3. advance
return prev # new head
# Dummy head when building or deleting
dummy = tail = ListNode()
...
tail.next = node; tail = node
return dummy.nextDraw it
In interviews, draw 3–4 boxes and arrows, and update them step by step for your loop. It's the fastest way to avoid losing a pointer. The order of the three assignments in reversal matters.
In this course's runner, list inputs like [1, 2, 3] are converted to ListNode chains for you, and returned lists are converted back to arrays.