Linked Lists Doubly linked lists
279. Insert Before a Given Node
You are given node, a node of a doubly linked list, and an integer value. Insert a new node holding
value directly before node. Your function returns nothing. It changes the list in place.
Your function gets only node. It does not get the head of the list. The given node is never the head, so
the head stays the same.
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 insert, both
directions must be right. The comment at the top of the starter code shows the node in your language.
The examples write a list as its values from the head on, so head = [4,1,6] is the list 4 ⇄ 1 ⇄ 6.
position says which node is node, counting the head as node 1. Your function never sees head or
position. After your function runs, the list is read from its head, and that is the output. The judge also
checks every prev pointer. If one is wrong, the output names the first node whose prev is wrong instead
of the values.
Example 1
Input: head = [5, -12, 30, 7], position = 3, value = 18
[5,-12,18,30,7]Explanation: The given node is the third node, which holds 30. The new node for 18 goes between -12 and 30. The node holding -12 now points forward to it, and the node holding 30 points back to it.
Example 2
Input: head = [40, 9], position = 2, value = -6
[40,-6,9]Explanation: The given node is the last node. The new node goes between the head and it, so the last node is still 9.
Example 3
Input: head = [-3, 14, -3, 8]
position = 3
value = -1000000000
[-3,14,-1000000000,-3,8]Explanation: Two nodes hold -3. The given node is the second of them, the third node, so the new node goes right before it, not before the first -3.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
2 ≤ number of nodes ≤ 105-109 ≤ Node.val, value ≤ 1092 ≤ position ≤ number of nodes
Clarifying questions
What you would ask an interviewer before writing any code.