Linked Lists Singly linked list basics
273. Remove Linked List Elements
You are given head, the first node of a singly linked list, and an integer val. Remove every node whose
value equals val, and return the head of the list that is left. The other nodes stay in their order. If
no node holds val, return the list unchanged. If every node holds it, return the empty list.
Delete the Node with Value X removes only the first match. Here every match goes.
A singly linked list is a chain of nodes. Each node holds a value and a pointer to the next node, and the last node's pointer is null. An empty list has no nodes, and its head is null.
The examples write a list as its values from the head on, so head = [4,1,6] is the list 4 → 1 → 6. The
output shows the list from the node you return, and shows an empty list as [].
Example 1
Input: head = [1, 7, 7, 3, 7, 5], val = 7
[1,3,5]Explanation: The value 7 sits in the second, third and fifth node. All three go, including the two that sit next to each other. The nodes holding 1, 3 and 5 stay in their order.
Example 2
Input: head = [-4, -4, 10, -4], val = -4
[10]Explanation: The first two nodes both hold -4, so the head goes and so does the node after it. The node holding 10 becomes the new head, and the last node goes too.
Example 3
Input: head = [9, 9, 9], val = 9
[]Explanation: Every node holds 9, so nothing is left and the answer is the empty list.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
0 ≤ number of nodes ≤ 105-109 ≤ Node.val ≤ 109-109 ≤ val ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.