LeetCode 203 · Linked list

Remove Linked List Elements, explained with a picture

Uncoupling every coach with one number.

Linked list
▶ Watch it step by step

The problem

Remove every node with a given value from a linked list.

Input:  1 → 2 → 6 → 3 → 4 → 5 → 6, remove 6
Output: 1 → 2 → 3 → 4 → 5

Picture it

Picture walking along a train and uncoupling every coach with the unwanted number, linking the coach before it straight to the coach after it. A dummy coach in front means even the first coach can be removed the same way.

Short version: the full lesson (brute force, complexity, edge cases and a quiz) is still being written. The animation is complete.

The key idea

Dummy head + skip matching nodes. O(n).

Python solution

def remove_elements(head, val):
    dummy = curr = Node(0, head)
    while curr.next:
        if curr.next.val == val:
            curr.next = curr.next.next
        else:
            curr = curr.next
    return dummy.next

In the interactive version each line lights up as the animation runs, and you can type your own input to see the algorithm handle it.