easyLinked lists target 15 min
Remove nodes with a given value
You get head, the first node of a linked list (or None if the list is empty), and an integer val. Each node is a ListNode with a value (node.val) and a link (node.next) to the node after it.
Take out every node that holds val. The other nodes stay, in their order. Return the first node that is left, or None if no node is left.
Examples write a linked list as the list of its values: [4, 2, 7] means 4 → 2 → 7, and [] is an empty list.
Example 1
Input
head = [4, 2, 7, 2, 5], val = 2Output[4, 7, 5]Both 2s are gone. The rest keep their order.
Example 2
Input
head = [3, 3, 1], val = 3Output[1]The first two nodes go, so the answer starts at the 1.
Example 3
Input
head = [6, 6], val = 6Output[]Every node goes: return None.
Constraints
0 ≤ number of nodes ≤ 104
1 ≤ node value ≤ 50
0 ≤ val ≤ 50
Plan it first
Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.