Lesson 10 of 40Core patterns
Linked Lists
Traverse, reverse and merge linked lists with careful pointer moves, and use fast and slow pointers to find middles and cycles.
Linked lists rarely appear in day-to-day application code, but they are an interview favourite because they test one skill directly: can you change pointers in the right order without losing part of your data? The same skill shows up later in trees, graphs and LRU caches. Get comfortable here and those feel easy.
Nodes and pointers
A linked list is a chain of nodes. Each node holds a value and a reference (a pointer) to the next node. The list is known only by its first node, the head. The last node points to None (Python) or null (TypeScript).
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.That while node loop is the traversal every linked list solution starts from. Reaching the k-th node takes k steps, so access by position is O(n). In exchange, inserting or removing a node you already hold is O(1): you just rewire pointers, nothing shifts.
In the practice problems, ListNode is already defined for you in both languages, and lists are passed in and out as heads.
What does this print?
class ListNode:
def __init__(self, val, next=None):
self.val = val
self.next = next
head = ListNode(4, ListNode(7, ListNode(9)))
total = 0
node = head
while node.next:
total += node.val
node = node.next
print(total)The dummy head
Many list operations have an awkward special case: what if the node you need to change is the head? A dummy (sentinel) node placed before the head removes that case. You build or edit the list after the dummy, then return dummy.next.
def remove_value(head, target):
dummy = ListNode(0, head)
prev = dummy
while prev.next:
if prev.next.val == target:
prev.next = prev.next.next # skip the node
else:
prev = prev.next
return dummy.next # works even if the old head was removedremove_value return dummy.next instead of head?Reversing a list in place
Reversal is the most asked linked list question. Walk the list once and flip each next pointer to point backwards. You need three pointers: prev (the reversed part so far), cur (the node you are flipping), and nxt (saved so you do not lose the rest of the list).
Start: nothing is reversed yet, so prev is None. cur is the head.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Put the four lines of the reversal loop body in order.
- Tap the steps below in the right order.
Reverse a Linked List
You get the head of a singly linked list. Reverse the list so the last node comes first, and return the new head. Do it in place by turning the existing next pointers around, without building a new list.
1 -> 2 -> 3 -> 4 -> 5 becomes 5 -> 4 -> 3 -> 2 -> 1
1 -> 2 becomes 2 -> 1
(empty) stays (empty)An empty list is None in Python and null in TypeScript.
Constraints
0 <= number of nodes <= 5000-5000 <= Node.val <= 5000
Fast and slow pointers
Move two pointers through the list at different speeds: slow one step at a time, fast two steps. When fast reaches the end, slow is at the middle.
Both start at the head.
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
# slow is the middle (the second middle for even lengths)1 → 2 → 3 → 4, where does slow end?Cycle detection (Floyd's algorithm). If a list has a cycle, the last node points back to an earlier one and a normal traversal never ends. Run the same fast and slow pointers: in a cycle, fast gains one step on slow every round, so it must eventually land on the same node. If fast reaches None instead, there is no cycle. That is O(n) time and O(1) space, versus O(n) space for a "seen" set of nodes.
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast: # same node object, not just equal values
return True
return FalsePractice it with the linked-list-cycle problem. The same pair of pointers also finds the k-th node from the end: start fast k steps ahead, then move both until fast hits the end.
Merging two sorted lists
To merge two sorted lists into one, keep a tail pointer starting at a dummy node. Repeatedly attach the smaller of the two front nodes to tail, advance that list, and advance tail. When one list runs out, attach the rest of the other in one step.
def merge(a, b):
dummy = tail = ListNode()
while a and b:
if a.val <= b.val:
tail.next, a = a, a.next
else:
tail.next, b = b, b.next
tail = tail.next
tail.next = a or b # attach whatever is left
return dummy.nextfunction merge(a: ListNode | null, b: ListNode | null): ListNode | null {
const dummy = new ListNode();
let tail = dummy;
while (a && b) {
if (a.val <= b.val) { tail.next = a; a = a.next; }
else { tail.next = b; b = b.next; }
tail = tail.next;
}
tail.next = a ?? b; // attach whatever is left
return dummy.next;
}It reuses the existing nodes, so it is O(n + m) time and O(1) extra space.
Merge Two Sorted Lists
You get the heads of two linked lists, a and b, each already sorted in ascending order. Splice them together into one sorted list and return its head. Reuse the existing nodes rather than making new ones.
a = 1 -> 2 -> 4, b = 1 -> 3 -> 4 → 1 -> 1 -> 2 -> 3 -> 4 -> 4
a = (empty), b = 0 → 0
a = (empty), b = (empty) → (empty)If both are empty, return None (null in TypeScript).
Constraints
0 <= number of nodes in each list <= 50-100 <= Node.val <= 100- Both lists are sorted in non-decreasing order.
Complexity and common mistakes
| Operation | Time | Extra space |
|---|---|---|
| Traverse, find, find middle | O(n) | O(1) |
| Insert or delete after a node you hold | O(1) | O(1) |
| Reverse in place | O(n) | O(1) |
| Merge two sorted lists | O(n + m) | O(1) |
| Cycle detection (Floyd) | O(n) | O(1) |
- Losing the rest of the list by overwriting
cur.nextbefore saving it. - Not handling
None/null: an empty list, a one-node list, or calling.nextonNone. Checkfast and fast.nextbeforefast.next.next. - Returning the old head after the head changed. Return
dummy.nextorprev. - Comparing values instead of nodes in cycle detection. Use
isin Python and===in TypeScript.
Which technique fits?
- node
- One element of a linked list: a value plus a pointer to the next node.
- head
- The first node. The whole list is reached from it.
- dummy head
- A placeholder node before the real head that removes special cases; return
dummy.next. - in-place reversal
- Flip each
nextpointer using prev, cur and nxt. O(n) time, O(1) space. - fast and slow pointers
- Two pointers moving at speeds 2 and 1. Finds the middle, cycles, and k-th from the end.
- Floyd's algorithm
- Cycle detection: if fast and slow ever meet, the list has a cycle.