Linked Lists Singly linked list basics
271. Delete the Node with Value X
You are given head, the first node of a singly linked list, and an integer x. Remove the first node that
holds the value x, the one closest to the head, and return the head of the list that is left. The other
nodes stay in their order. If no node holds x, return the list unchanged.
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 = [8, -3, 5, -3, 12], x = -3
[8,5,-3,12]Explanation: The value -3 sits in the second and the fourth node. Only the second node is removed, so 8 now points to 5. The later -3 stays.
Example 2
Input: head = [6, 2, 9], x = 6
[2,9]Explanation: The head holds 6, so the head is removed. The node holding 2 is the new head.
Example 3
Input: head = [4, 7, 1], x = 5
[4,7,1]Explanation: No node holds 5, so the list comes back as it was.
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 ≤ x ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.