183. Remove Linked List Elements
Your function receives the head of a singly linked list and an integer val. Delete every node whose stored value equals val, keep the surviving nodes in their original order, and return the head of the resulting list.
Matches can appear anywhere — at the front, in the middle, at the tail, or back to back — and the answer may even be an empty list if every node matches. The tricky part is that removing the head changes what you return, while removing any other node only rewires a next pointer.
Example 1:
Input: head = [1, 2, 6, 3, 4, 5, 6], val = 6
Output: [1, 2, 3, 4, 5]
Explanation: Both nodes holding 6 are unlinked; the rest keep their relative order.
Example 2:
Input: head = [7, 7, 7, 7], val = 7
Output: []
Explanation: Every node matches val, so nothing survives and the returned list is empty.
Constraints:
- 0 ≤ number of nodes ≤ 10⁴
- 1 ≤ node value ≤ 50
- 0 ≤ val ≤ 50
Hints:
Deleting a middle node is one pointer write: `prev.next = curr.next`. What makes the head node special, and how could a fake node placed *before* the head make it not special at all?
Attach a sentinel (dummy) node in front of the head. Now every deletable node has a predecessor, one uniform loop handles everything, and the answer is simply `sentinel.next`. Alternatively, recursion states it in two lines: clean the tail first, then decide whether the current node stays.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: head = [1, 2, 6, 3, 4, 5, 6], val = 6
Expected output: [1, 2, 3, 4, 5]