Linked Lists Doubly linked lists
285. Delete Every Occurrence of a Key
You are given head, the first node of a doubly linked list, and an integer key. Delete every node whose
value equals key, and return the head of the list that is left. The other nodes stay in their order. If no
node holds key, return the list unchanged. If every node holds it, return the empty list.
Each node has a value, val, and two pointers. next points to the following node, and prev points to the
node before it. The head's prev is null, and the last node's next is null. After the deletes, both
directions must still be right. The comment at the top of the starter code shows the node in your language.
Remove Linked List Elements is the same task on a singly linked list. Here every node also points back.
The examples write a list as its values from the head on, so head = [4,1,6] is the list 4 ⇄ 1 ⇄ 6, and the
output shows the list you return the same way, with [] for the empty list. The judge also checks every
prev pointer. If one is wrong, the output names the first node whose prev is wrong, counting the head as
node 1, instead of the values.
Example 1
Input: head = [4, 9, 4, 4, 1, 4], key = 4
[9,1]Explanation: Four nodes hold 4: the head, the two in a row in the middle, and the last node. All of them go. The node
holding 9 becomes the head, with its prev null, and the node holding 1 becomes the last node.
Example 2
Input: head = [-6, -6, -6], key = -6
[]Explanation: Every node holds -6, so nothing is left and the answer is the empty list.
Example 3
Input: head = [10, -1000000000, 0], key = -5
[10,-1000000000,0]Explanation: No node holds -5, so the list comes back unchanged.
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 ≤ key ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.