AlgoFrames

Delete by value

Standard · Write code · about 10 min

Given the head of a singly linked list and a value val, remove every node whose value equals val. Return the head of the list that remains (null when every node is removed).

Example 1

Input:

[[6,2,6,3,6],6]

Output:

[2,3]

The head itself is one of the nodes to remove.

Example 2

Input:

[[1,2,3],4]

Output:

[1,2,3]

Nothing matches, so the list is unchanged.

Constraints

  • 0 ≤ number of nodes ≤ 5,000
  • -1,000 ≤ node value, val ≤ 1,000

Learn the idea first: Singly linked lists: traverse, insert, delete, a visual lesson.

More Singly linked lists: traverse, insert, delete problems