Remove Linked List Elements

easy

You are given the head of a singly linked list and an integer val. Remove every node whose value equals val and return the head of the resulting list.

A node is removed by re-routing the list around it, so the nodes you keep stay in their original order. If every node matches — or the list is empty to begin with — return an empty list (a null head).

Matches can appear anywhere: at the front, in the middle, in a run of consecutive nodes, or at the very end.

Hints

A node in the middle is easy to delete because something points at it. What does the very first node lack?
What if you could guarantee that every node — even the head — had a predecessor to re-route around it?
Place one throwaway node before the head. Now a single loop splices out matches uniformly, and you return the throwaway's next.

Common doubts

In garbage-collected languages (Python, JavaScript, Go) dropping the reference is enough. In C++ you may delete the spliced-out node to avoid a leak, though the judge only checks the returned list.
Yes — that is exactly why you do not advance prev after a removal. Keep prev fixed and re-check the new prev.next, which may also match.
Return the empty list. With a sentinel, dummy.next is already null, so the same code handles it with no special case.

Interview follow-ups

Replace curr.val == val with any predicate; the sentinel-and-splice skeleton is unchanged. This generalizes to filtering a linked list in place.
Yes: recurse on head.next to clean the tail, then return that tail if head.val == val, else attach head in front. Elegant, but it uses O(n) call-stack space.

Fun facts

  • The sentinel (dummy head) node is one of the most reused tricks in linked-list problems — it turns 'the head is special' into 'the head is ordinary'.
  • The same guard-node idea powers doubly linked lists, LRU caches, and skip lists, where sentinels at both ends erase every empty-list edge case.

Asked at

AmazonMicrosoftGoogleAdobeBloomberg
Frequently Sometimes Occasionally
Example 1
Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]
Both nodes equal to 6 are removed; the survivors keep their order.
Example 2
Input: head = [], val = 1
Output: []
An empty list stays empty.
Example 3
Input: head = [7,7,7,7], val = 7
Output: []
Every node matches, so the whole list is removed.
Constraints

- The number of nodes in the list is in the range [0, 10^4]. - 1 <= Node.val <= 50 - 0 <= val <= 50

Solve this problem →