Community Problem

Remove Linked List Elements

Difficulty: Easy

Delete every node in a singly-linked list whose value matches a target, with a sentinel/dummy node that makes the head case fall out of the general loop.

Remove Linked List Elements

Delete every node in a singly-linked list whose value matches a target, with a sentinel/dummy node that makes the head case fall out of the general loop.

EASY
Free
linked-list
recursion
jameszhang

By @jameszhang

January 17, 2026

·

Updated May 18, 2026

699 views

19

4.5 (9)

Used this in mock interviews dozens of times because it's the cleanest place to drill the dummy/sentinel pattern that EVERY linked-list problem with deletion needs. The mistake I see weekly: special-casing the head with an if chain at the top instead of attaching a sentinel and letting one loop handle every case.

Remove Linked List Elements

Given the head of a singly-linked list and an integer val, remove every node whose Node.val == val and return the new head. The relative order of remaining nodes must be preserved.

Examples

Example 1:

  • Input: head = [1, 2, 6, 3, 4, 5, 6], val = 6
  • Output: [1, 2, 3, 4, 5]
  • Explanation: Both 6s are removed.

Example 2:

  • Input: head = [7, 7, 7, 7], val = 7
  • Output: []
  • Explanation: All four nodes match and are removed.

Example 3:

  • Input: head = [], val = 1
  • Output: []
  • Explanation: Empty list stays empty.

Example 4:

  • Input: head = [1, 2, 3], val = 4
  • Output: [1, 2, 3]
  • Explanation: No node matches, list unchanged.

Constraints

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

Follow-up

Why is the dummy / sentinel pattern strictly cleaner than a head-special-case loop? The sentinel makes the head's predecessor explicit, so the deletion code is a single prev.next = prev.next.next regardless of whether the deleted node is the head or interior.

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems