Use dummy heads to filter, partition, split and add lists, and sort a list with merge sort.
You work on the platform behind an online store. Your team lead brings six chain jobs:
Each of them rebuilds a chain by moving nodes, and none of them needs more than one or two walks. The tool that makes them short is a node that holds no data: a placeholder (also called a dummy head).
A sorter has a pile of letters. She puts light ones on the left tray and heavy ones on the right. Each letter goes on top of the last one in its tray, so the order inside a tray does not change. At the end she stacks the right tray under the left one.
A chain does the same. The trays are two chains, and the top of each tray is a tail cursor. An empty tray has a card on it that is never part of the mail: the placeholder.
Two trays: each letter goes on top of the last one in its tray, so the order inside a tray is kept. Then the trays are stacked.
A chain has a head, the first real node. Removing the head means the variable head itself must change, and everything that held the old head must hear about it. Any other node is removed by changing the next of the node before it.
A placeholder removes that difference. It is an extra node in front of the head. It is never part of the answer, so its next is always the head, and the answer is placeholder.next.
Step by step: A placeholder node sits in front of the first value. The animated player loads in your browser.
tail.next = node and then tail = node.Predict what happens
Q A cart chain is 4, 7, 2. You remove the head, 4, with a placeholder in front. Which node's next changes?
Answer: B
The placeholder is the node before the head, so it is bypassed like any other. Its next moves from 4 to 7, and the answer is the placeholder's next.
Walk the chain with two cursors. prev is the last kept node and curr is the next node to inspect, and prev starts on the placeholder. If curr matches, set prev.next = curr.next. If it does not, prev moves to curr. In both cases curr moves on.
Take 4, 7, 7, 2, 7 and remove the 7s. The first 7 is bypassed, and prev stays on 4. The second 7 is bypassed the same way, and then 2 is kept. The last 7 is bypassed and 2 points at null, so the result is 4, 2.
Why does prev stay put after a bypass? The node after the bypassed one has not been looked at yet, and it must hang from the last kept node. If prev moved onto the bypassed node, the next bypass would edit a node that is no longer in the chain. The result would be [4, 7, 2] instead of [4, 2].
Step by step: Delete the head, 4. The animated player loads in your browser.
Filter: prev stays on the last kept node, and every match is bypassed by pointing prev at the node after it.
Predict what happens
Q A chain is 3, 3, 3 and you remove every 3. How many times does prev move?
Answer: C
Every node matches, so every node is bypassed and prev is never moved. The answer is the placeholder's next, which is null.
Exercise · Put it in order: Take every line out of a cart. Arrange the lines into a function that removes every node with a given value from a list and returns the new head, using a placeholder.
def remove_all(head, target):
dummy = ListNode(0, head)
prev = dummy
curr = head
while curr:
if curr.val == target:
prev.next = curr.next
else:
prev = curr
curr = curr.next
return dummy.next
prev = currTo put the nodes below a pivot first, keep two chains, each with its own placeholder and tail. Walk the original chain once. Each node is appended to the back of one of the two chains. The order inside each chain is the arrival order.
At the end, join the first chain's tail to the second chain's first node. One more step is needed: the last node of the second chain may still point at a node of the old chain, so set its next to null. If you skip it, the new chain can point into itself.
Take 5, 1, 8, 3, 9, 2 and the pivot 5. The small chain gets 1, 3, 2 and the other chain gets 5, 8, 9. Joined, the answer is 1, 3, 2, 5, 8, 9. Without the cut, the node 9 still points at 2, and a walk goes 1 → 3 → 2 → 5 → 8 → 9 → 2 → 5 → ... and never ends.
The same two chains solve the odd and even problem. Instead of testing a value, you alternate: the first node goes to one chain, the second to the other, and so on. That version uses two cursors that skip over each other, and no placeholders.
Partition: build a light chain and a heavy chain at their tails, cut the last heavy node, then join light to heavy.
Exercise · Find the bug: The parcel that is not lighter. This function puts the parcels lighter than the pivot first, then all the others, and each group keeps its order. A parcel exactly as heavy as the pivot lands in the wrong place. Which line is wrong?
def partition(head, pivot):
light_head = ListNode(0)
heavy_head = ListNode(0)
light = light_head
heavy = heavy_head
curr = head
while curr:
if curr.val <= pivot:
light.next = curr
light = curr
else:
heavy.next = curr
heavy = curr
curr = curr.next
heavy.next = None
light.next = heavy_head.next
return light_head.nextTo cut a chain into k parts, first count it with one walk, so you know n. Every part gets n // k nodes, and the first n % k parts get one more. Then walk again. For each part, walk to its last node, remember the node after it, and set the last node's next to null.
With 8 nodes and k = 3, the sizes are 3, 3 and 2. A part of size 0 has no last node and must be skipped, which happens when k is larger than n. Take the chain 5, 9, 2, 7, 1, 8, 3, 6. Giving the extra nodes to the last parts instead of the first gives [[5, 9], [2, 7, 1], [8, 3, 6]], with the wrong sizes.
Step by step: The split point of six nodes. The animated player loads in your browser.
Predict what happens
Q A chain has 10 nodes and you cut it into k = 4 parts. What are the part sizes?
Answer: C
10 // 4 = 2 and 10 % 4 = 2. Every part gets 2, and the first two parts get one more: 3, 3, 2, 2.
Exercise · Break it: Find the input that cuts the wrong sizes. This function cuts a list into k parts. It gives every part n // k nodes and hands the leftover nodes to the last part. Find an input where it gives the wrong answer or crashes.
def split_parts(head, k):
n = 0
curr = head
while curr:
n += 1
curr = curr.next
base = n // k
extra = n % k
parts = []
curr = head
for i in range(k):
parts.append(curr)
length = base + (extra if i == k - 1 else 0)
for _ in range(length - 1):
curr = curr.next
if curr:
nxt = curr.next
curr.next = None
curr = nxt
return partsChains of digits, lowest digit first, are already in the order that column addition uses. Walk both chains together with a carry. Each column adds the carry and the digits that are still there, writes total % 10 as a new node at the tail, and keeps total // 10 as the next carry.
The loop must run while either chain has a digit or the carry is not 0. Take 6, 1, 5 and 7, 8, which are 516 and 87. The columns give 3 (carry 1), then 0 (carry 1), then 6 (carry 0): the chain 3, 0, 6, which is 603. A loop that stops when both chains end drops a last carry: 99 + 1 gives [0, 0], and the right answer is [0, 0, 1].
Add digit chains: each column adds the carry and the digits that are left, writes one digit, and keeps the rest as the next carry.
Exercise · Predict the output: What do the digit nodes read?. Two chains hold digits with the lowest digit first: 8 → 9 → 9 is 998, and 7 → 5 is 57. The code adds them column by column and prints the new chain. What does it print?
class Node:
def __init__(self, val, nxt=None):
self.val, self.next = val, nxt
a = None
for d in [9, 9, 8]:
a = Node(d, a)
b = None
for d in [5, 7]:
b = Node(d, b)
dummy = tail = Node(0)
carry = 0
while a or b or carry:
total = carry
if a:
total += a.val
a = a.next
if b:
total += b.val
b = b.next
tail.next = Node(total % 10)
tail = tail.next
carry = total // 10
node = dummy.next
while node:
print(node.val, end=" ")
node = node.nextA chain has no index, so the sorts that swap entries by position do not fit. Merge sort does. Split the chain at its middle with slow and fast, and sort each half the same way. Then merge the two sorted halves with a placeholder and a tail: take the smaller front each time.
Each level of the recursion walks every node once to split and once to merge. For 10^5 nodes there are 17 levels, so the cost is about 2 × 17 × 10^5 = 3,400,000 steps. Insertion sort on a sorted chain of 10^5 nodes costs 4,999,950,000 comparisons.
Start fast one node ahead of slow. With two nodes, a fast on the head ends with slow on the second node, so the first half is the whole chain and the recursion never ends. Python stops it with a RecursionError.
Merge two sorted halves: take the smaller front each time, and attach what is left when one half runs out.
Predict what happens
Q In the merge step, one half runs out first. What must you do?
Answer: B
Everything left in the other half is larger than what was taken, and it is sorted. One assignment, tail.next = the rest, finishes the merge. Without it the leftover nodes are lost: the chain 3, 1, 2 would give [1].
| Operation | Rebuilding the chain | The plain alternative |
|---|---|---|
| Remove every match: search the whole chain | O(n) time, O(1) memory: one walk | Restart from the head after each removal: O(n × m) |
| Remove the head, at the front | O(1): the placeholder makes it a normal bypass | A special case for the head in every loop |
| Append to the back of a result chain | O(1) with a tail cursor | Walk to the end each time: O(n) |
| Find the middle with slow and fast | O(n) time, O(1) memory: one walk | Count, then walk to n / 2: two walks |
| Reach a node by index | O(i): one hop per node | Copy to an array first: O(n) time and memory |
| Partition around a value | O(n) time, O(1) memory: two tails | Read each value by position: O(n²) |
| Odd positions, then even | O(n) time, O(1) memory | Read each position by a walk: O(n²) |
| Split into k parts | O(n + k): count, then cut as you go | Read each part by position: O(n²) |
| Add two digit chains | O(n + m) time, a new chain for the answer | Convert to integers: fails beyond the integer range |
| Sort the chain | O(n log n) time, O(log n) recursion | Insertion sort: O(n²) |
Every plain alternative pays for reading by position, and a chain has no positions. The fix is always the same: walk once and keep a cursor where the work happens.
Drive the chain yourself and watch the hop counter. The sandbox shows a delete and the middle, which are the two moves under this lesson. The partition, the carry and the merge are drawn in the lecture and the clips.
Try these five, in order:
The sandbox: build a list and run its operations step by step. It loads in your browser.
Now build a list that keeps a placeholder in front of its first value. The lab gives you a Node class and a PlaceholderList class with before (the placeholder), tail and count. You write push_back, remove_all, partition, sort and size. The sixth method, to_list, is written for you.
remove_all needs the filter walk. partition needs two chains and the cut. sort needs the split, the recursion and the merge. All of them reuse the same nodes.
Three rules keep the list correct:
before is never part of the list. The first value is before.next.tail always points at the last node, or at the placeholder when the list is empty. After remove_all, partition and sort, it must be set again.count changes only in push_back and remove_all.Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
Use a placeholder and tails when a task rebuilds a chain by moving nodes: filtering, partitioning, merging, splitting, adding digit by digit. One walk and a few cursors are enough, and no node is copied.
In an interview, say "I will use a placeholder so the head is not a special case" before you write code. It shows that you have seen the problem class.
If the data is in an array, filtering, partitioning and sorting are easier there, and indexes are free. A chain rebuild pays off when the nodes must stay where they are in memory, or when the data arrives as a chain.
If the order inside a group does not matter, you can often swap nodes in place with fewer cursors, and the two-chains method is more than you need.
if curr.val == target:
prev.next = curr.next
prev = curr # runs for matches too
curr = curr.nextOn the cart 4, 7, 7, 2, 7 with target 7 this returns [4, 7, 2] instead of [4, 2]. After the first bypass, prev stands on a node that is no longer in the chain. Move prev only when the node is kept.
The mistake: moving prev after a bypass puts it on a node that is no longer in the chain, so the next bypass edits a dead node.
light_tail.next = heavy_head.next # join
return light_head.next # heavy_tail.next was never set to nullOn 5, 1, 8, 3, 9, 2 with the pivot 5, the node 9 still points at 2, which is already on the first chain. A walk goes 1 → 3 → 2 → 5 → 8 → 9 → 2 → 5 → ... for ever. Set the second chain's last next to null before you join.
while left and right: ... # stops when one side ends
return start.next # the other side is lostFor the chain 3, 1, 2 the sort returns [1] instead of [1, 2, 3]. In digit addition, the same shape of mistake is a loop that stops when both chains end: 99 + 1 gives [0, 0]. After the loop, attach the rest, or run the loop while a carry is left.
slow = head
fast = head # should be head.nextFor two nodes, slow ends on the second node, so the first half is the whole chain and the recursion never shrinks. Python stops it with a RecursionError. Start fast one node ahead, so the first half is the larger half and the second half is never the whole chain.
prev on the last kept node and bypass matches. prev moves only for a kept node.Explain the idea in your own words, then take the checkpoint quiz.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · The placeholder and the filter
Q1/2 What is the main job of a placeholder node in front of the head?
Answer: B
The placeholder holds no data. Every node, including the head, then has a node before it, and the answer is the placeholder's next.
Q2/2 You remove every 7 from 5, 7, 7, 8. After the first 7 is bypassed, where is prev?
Answer: C
A bypass does not move prev. The second 7 still has to be looked at, and it must hang from 5.
Checkpoint · Two chains and the cut
Q1/3 You partition 6, 2, 7, 2, 9, 1 around the pivot 6, with less than 6 first. What is the result?
Answer: C
The nodes below 6 are 2, 2, 1 in arrival order. The others are 6, 7, 9 in arrival order. Each group keeps its order, and nothing is sorted.
Q2/3 Before joining the small chain to the other chain, which next must be set to null?
Answer: B
The last node on the second tail still has its old next. If that node is on the first chain, the new chain points into itself and a walk never ends.
Q3/3 In the odd and even problem, which positions go in the first group?
Answer: B
Only positions matter, never the values. The first, third and fifth nodes come first, then the second, fourth and sixth.
Checkpoint · The carry and the split
Q1/2 You add the digit chains 9, 9 and 1 (that is 99 plus 1). How many nodes does the answer have?
Answer: B
The columns give 0 (carry 1), 0 (carry 1), and then a carry of 1 is written as the third digit. The answer is 0, 0, 1, which is 100.
Q2/2 A chain has 13 nodes and you cut it into k = 5 parts. What are the part sizes?
Answer: C
13 // 5 = 2 and 13 % 5 = 3. Every part gets 2, the first three parts get one more: 3, 3, 3, 2, 2.
Checkpoint · Merge sort on a chain
Q1/3 In the split step of merge sort, where does fast start, and why?
Answer: B
With both on the head, two nodes leave slow on the second node and the first half is the whole chain. That never shrinks.
Q2/3 The merge loop ends because the left half is used up. What finishes the merge?
Answer: B
The rest of the right half is sorted and larger than everything taken. Attaching it is one assignment.
Q3/3 Roughly how many levels does merge sort have on 100,000 nodes?
Answer: C
Each level halves the pieces, and the 17th halving leaves pieces of one node. Each level walks every node twice, to split and to merge, so the cost is about 2 × 17 × n steps.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Sandbox and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.