Linked List · Pattern 1 of 5

Dummy node: no special case for the head

Put a fake node in front of the head. Now every real node, the head included, has a node before it, so deleting, swapping or building a list needs no special case. Return dummy.next at the end.

3 variations · 8 problems · 7 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • The head itself may be deleted, swapped or replaced
  • You build a new list node by node (merging, adding numbers)
  • Your code has an if (node == head) branch you would like to remove

The template

Dummy Node Pattern
// delete every node with value val
ListNode removeElements(ListNode head, int val) {
    ListNode dummy = new ListNode(0);
    dummy.next = head;
    ListNode prev = dummy;                          // the last node we keep
    while (prev.next != null) {
        if (prev.next.val == val) prev.next = prev.next.next;   // unlink, do not move
        else prev = prev.next;
    }
    return dummy.next;                              // the head may have been deleted
}

// build a new list behind a tail pointer
ListNode mergeTwoLists(ListNode a, ListNode b) {
    ListNode dummy = new ListNode(0), tail = dummy;
    while (a != null && b != null) {
        if (a.val <= b.val) { tail.next = a; a = a.next; }
        else { tail.next = b; b = b.next; }
        tail = tail.next;
    }
    tail.next = (a != null) ? a : b;                // attach what is left
    return dummy.next;
}

The variations

  1. 1Delete nodes while walking

    Stand on the node before the one you test. If prev.next must go, skip it with prev.next = prev.next.next and stay put; otherwise step forward. For duplicates in a sorted list, skip the whole run of equal values.

  2. 2Build a new list behind a tail

    Keep a tail pointer that starts at the dummy. Each step, hang the next node on tail.next and move tail. For adding numbers, the new node holds sum % 10 and the carry moves on.

    Now you solve
  3. 3Rewire around the head

    When the first nodes change places, the dummy gives you a fixed node before them. Swap a pair by changing three pointers, then jump two ahead. Rotating is "find the new tail, cut, and attach the old tail to the old head".

Mistakes to avoid

  • Moving prev forward right after deleting: two matching nodes in a row, and the second one survives.
  • Returning head instead of dummy.next when the old head was removed.
  • Adding two numbers: forgetting the final carry, which needs one more node.
Next: Fast and slow pointers: middles and cycles →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.