The dummy node trick
1 The head has no node before it
A linked list is like a train. Each coach is coupled to the coach behind it, and head holds the first coach. To take a coach out, we go to the coach in front of it and couple it to the coach after. In code, that is prev.next = prev.next.next, from the linked lists lesson.
The first coach has no coach in front of it. So removing the head needs code of its own. Here we remove every node with the value 6:
With the head as a special case, the pseudocode looks like this:
removeElements(head, val):
while head is not null and head.val == val:
head = head.next // the head has no prev
if head is null:
return null
prev = head
while prev.next is not null:
if prev.next.val == val:
prev.next = prev.next.next
else:
prev = prev.next
return head
The first loop is easy to forget. Without it, this list comes back as 6 → 2 → 9. The second loop only checks prev.next, and the head is nobody's next. An if in place of the first while gives the same wrong answer, because the second 6 becomes the new head.
Inserting before the head has the same problem. Every change at the head needs its own branch.
2 A dummy node in front
A train has an engine at the front. The engine is never taken out, so every coach has something in front of it.
The dummy node is that engine. It is a node we make ourselves, with any value, and its next is the head:
Now every real node, the head too, has a node before it. So one loop handles them all. prev starts at the dummy, and at each step we look at prev.next:
- It holds val. We unlink it with
prev.next = prev.next.next.prevstays where it is, because the newprev.nextmay hold val too. - It does not. We move
prevone node on.
The loop stops when prev.next is null. The node being checked is blue:
The two 6s at the head went out through the same line as the 6 in the middle. No branch for the head is left.
The answer is dummy.next, not head. Here head still points to the first 6, which is no longer in the list. dummy.next is always the first node that is left.
3 The code and its cost
This is the problem Remove Linked List Elements, with a dummy:
C++
Free what you unlink. removed keeps the node's address after it leaves the list, and delete removed frees it. The dummy is a plain local variable, ListNode dummy(0, head), so it needs no delete.
&ListNode{Next: head} makes the dummy. Its Val is left at 0, Go's zero value.
take() unlinks. prev.next.take() lifts the matching node out and leaves None behind, and prev.next = removed.next hands its rest back. The dummy is a Box, so prev has the same type at the dummy as at every real node.
Each node is checked once, so the time is O(n). The dummy is one extra node and prev is one pointer, however long the list is. So the extra space is O(1).
4 Building a list: a dummy and a tail
Some problems build a new list out of old nodes. In Merge Two Sorted Lists, two sorted lists become one sorted list, made of the same nodes. We build it like a train behind an engine. The dummy is the engine, and tail holds the last coach, where the next one gets coupled.
Without the dummy, the first node we attach becomes the head, and that needs its own if. With it, every attach is the same two lines:
tail.next = node
tail = tail.next
For the merge, a and b point at the front of each list. At each step we attach the smaller front node and move its pointer on:
When one list runs out, the rest of the other is already sorted. So one tail.next attaches all of it, and the answer is dummy.next.
Add Two Numbers builds its answer the same way, one new digit node at a time. A problem that splits a list in two, such as odd and even positions, keeps two dummies and two tails, and joins them at the end.
5 Reversing: flip one arrow at a time
Reversing a list moves no values. Every arrow turns around, and the last node becomes the head.
We do it the way a railway yard moves coaches to another track. We take the front coach off the old train and couple it to the front of a new train. Then we take the next one. The first coach taken ends up at the back. Halfway through 4 → 7 → 2 → 9, the list is in two parts:
Three pointers do the work:
prevholds the front of the reversed part. It starts at null, because nothing is reversed yet.curholds the front of the rest, the next node to move. It starts at the head.nextsaves the node aftercur, beforecur.nextchanges.
One turn of the loop moves one node, in four lines. Here is the second turn, which moves 7:
Step 3 is why next comes first. Once 7 points to 4, the arrow from 7 to 2 is gone. Only next still knows where 2 and 9 are. Without it, they are lost.
6 The trace, the code and the cost
The whole run on 4 → 7 → 2 → 9:
| turn | cur | next | cur.next becomes | reversed part | rest |
|---|---|---|---|---|---|
| 1 | 4 | 7 | null | 4 | 7 → 2 → 9 |
| 2 | 7 | 2 | 4 | 7 → 4 | 2 → 9 |
| 3 | 2 | 9 | 7 | 2 → 7 → 4 | 9 |
| 4 | 9 | null | 2 | 9 → 2 → 7 → 4 | empty |
At the end of each turn, prev moves to cur, the front of the reversed part. After the fourth turn, cur is null and the loop stops. prev holds 9, the new head, so we return prev. This is Reverse Linked List:
C++
take() does the saving. node.next.take() hands over the rest of the list and leaves None in its place. while let Some(mut node) = cur moves each node out of cur, so every node has exactly one owner at each step.
Each node moves once, so the time is O(n). We keep three pointers however long the list is, so the extra space is O(1).
Reversal can also be written with recursion. We reverse everything after the head first. Then the node after the head, now the last of the reversed rest, points back to the head, and the head points to null:
reverse(head):
if head is null or head.next is null:
return head
newHead = reverse(head.next)
head.next.next = head
head.next = null
return newHead
It is shorter, but every node waits on the call stack, so it takes O(n) space. On 10⁵ nodes the calls go 10⁵ deep, which can overflow the stack and give a Runtime Error.
7 Reversing part of a list
Reverse Linked List II reverses only positions left to right, counting from 1. It needs both ideas. Here we reverse positions 2 to 4 of 4 → 7 → 2 → 9 → 6, and the answer is 4 → 9 → 2 → 7 → 6.
Two nodes are saved before the reversal:
beforeis the node just ahead of the part. We reach it by walking left − 1 steps from the dummy.firstis the part's first node. After the reversal, it is the part's last node.
Then the same loop runs right − left + 1 times, starting with cur at first. Afterwards, prev holds the part's new front and cur holds the node after the part. The part is blue:
After the loop, the part is cut off at both ends. 4 still points to 7, and 7 points to null. The two lines in step 3 join both ends again.
When left is 1, the part starts at the head, and before is the dummy. The same two lines work, and the answer is dummy.next. Without the dummy, this case needs its own if. Reverse Nodes in k-Group repeats these moves for each group of k nodes.
8 Mistakes, and when to use it
- Returning
dummy. The answer starts with the dummy's value. Removing 6 from 6 → 6 → 2 → 6 → 9 gives 0 → 2 → 9 instead of 2 → 9. - Moving
prevafter an unlink. The newprev.nextnever gets checked, so on 6 → 6 → 2 → 6 → 9 the second 6 stays. On 2 → 6,prevmoves to null after the unlink, and the next check crashes with a Runtime Error. - Not saving
next. Aftercur.next = prev, the linecur = cur.nextwalks back into the reversed part. On 4 → 7 → 2 → 9, the loop stops after one turn and returns 4 alone. - Returning
headafter a reversal. The old head is now the last node, so the answer is 4 alone again. Returnprev. - Not cutting the last node. A node moved to a new list keeps its old
next. A split that puts the nodes below 5 first turns 8 → 1 → 3 into 1 → 3 → 8. But 8 still points to 1, its old next. That is a cycle, and printing the answer never ends. Set the last tail'snextto null.
The sign for this subtopic is an answer made of the same nodes, connected in a different order:
- The head may change. It may be removed, or a node may go in front of it. Put a dummy before it.
- The answer is a new list of picked nodes, as in merging, splitting or adding digits. Build it with a dummy and a tail.
- The order turns around, for the whole list, a part or groups of k. Use
prev,curandnext.
Some problems need all three, with the middle found by the fast and slow pointers of the last lesson.
dummy.next.Practice it
- Reverse Linked ListEasy
- Merge Two Sorted ListsEasy
- Reorder ListMedium
- Add Two NumbersMedium
- Rotate ListMedium
- Sort ListMedium
- Copy List with Random PointerMedium
- Reverse Nodes in k-GroupHard
- Odd Even Linked ListMedium
- Reverse Linked List IIMedium
- Plus One Linked ListMedium
- Next Greater Node In Linked ListMedium
- Sort a linked list of 0s, 1s and 2sMedium
- Flatten a linked listHard
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.