Skip to problem
←

Remove Linked List Elements

Easy 0 attempts

Given the head of a singly linked list and an integer val, remove every node whose value equals val. Return the head of the remaining list.

Keep every other original node in its original relative order. Reuse those nodes without changing their values or creating replacements. The input is not necessarily sorted.

The head may change when leading nodes are removed. Return null for an empty input or when every node is removed. If no value matches, return the unchanged list.

For [6, 6, 1, 6, 2] with val = 6, the result is [1, 2]. Consecutive matches must all be removed. Examples show value arrays, but the function receives nodes with val and next properties.

Function contract

Implement removeElements(head, val). Linked lists use value arrays. The editor passes nodes with val and next properties; [] becomes null.

Output: Return the head of the original surviving nodes in their original order, or null if none remain.

Example 1

Input
head = [1,2,6,3,4,5,6]
val = 6
Output
[1,2,3,4,5]

Example 2

Input
head = [7,7]
val = 7
Output
[]
Constraints
  • 0 to 10^4 nodes
  • 1 <= Node.val <= 50
  • 0 <= val <= 50
Topics

Dummy Head and a Predecessor Pointer

Create a temporary dummy node pointing to the head. Keep curr immediately before the next node to inspect, which lets the same code remove both leading and interior nodes.

If curr.next matches the target, bypass it. Do not advance curr after a removal: the following node may also match. If it does not match, retain it by advancing curr.

The loop preserves the relative order and values of every retained node. Return dummy.next, which may now be a different original node or null. The dummy itself is never included in the result.

javascript
function removeElements(head, val) {
  const dummy = { next: head };
  let curr = dummy;
  while (curr.next) {
    if (curr.next.val === val) curr.next = curr.next.next;
    else curr = curr.next;
  }
  return dummy.next;
}

Time: O(n) | Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript