The dummy node trick

Video lessonComing soon

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:

6head6269
Remove every 6. The answer is 2 → 9

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:

Ddummy6head6269
D is the dummy. Its value is never read

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. prev stays where it is, because the new prev.next may hold val too.
  • It does not. We move prev one node on.

The loop stops when prev.next is null. The node being checked is blue:

Removing every 6 with a dummy
6val
Dprev66269
prev.next is 6: unlink it

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:

Merging 2 → 8 and 3 → 5
2a8
a
3b5
b
Dtail
Start: tail is the dummy

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:

7prev4
Reversed part
2cur9
The rest

Three pointers do the work:

  • prev holds the front of the reversed part. It starts at null, because nothing is reversed yet.
  • cur holds the front of the rest, the next node to move. It starts at the head.
  • next saves the node after cur, before cur.next changes.

One turn of the loop moves one node, in four lines. Here is the second turn, which moves 7:

One turn of the loop: moving 7
4prev
Reversed part
7cur29
Before the turn: cur is 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:

turncurnextcur.next becomesreversed partrest
147null47 → 2 → 9
27247 → 42 → 9
32972 → 7 → 49
49null29 → 2 → 7 → 4empty

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:

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:

  • before is the node just ahead of the part. We reach it by walking left − 1 steps from the dummy.
  • first is 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:

Reversing positions 2 to 4
D4before7first296
Walk 1 step from D: before is 4

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 prev after an unlink. The new prev.next never gets checked, so on 6 → 6 → 2 → 6 → 9 the second 6 stays. On 2 → 6, prev moves to null after the unlink, and the next check crashes with a Runtime Error.
  • Not saving next. After cur.next = prev, the line cur = cur.next walks back into the reversed part. On 4 → 7 → 2 → 9, the loop stops after one turn and returns 4 alone.
  • Returning head after a reversal. The old head is now the last node, so the answer is 4 alone again. Return prev.
  • 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's next to 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, cur and next.

Some problems need all three, with the middle found by the fast and slow pointers of the last lesson.

When the head can change, start with a dummy, and return dummy.next.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.