Linked Lists Doubly linked lists
276. Insert Before the Head
You are given head, the first node of a doubly linked list, and an array values. Take the values one at a
time, in the order they appear in values, and insert each one before the head: a new node holding the value
becomes the first node, in front of the node that was first before it. Return the head of the list after
every value is inserted.
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. Every insert must keep both
directions right. The comment at the top of the starter code shows the node in your language.
Each new node goes in front of the one inserted just before it, so the inserted values end up in reverse order, ahead of the nodes the list started with. If the list is empty, the first new node becomes the whole list.
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. 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 = [7, -2, 15], values = [4, -9]
[-9,4,7,-2,15]Explanation: The node for 4 goes in front of 7, and the node holding 7 now points back to it. Then the node for -9 goes
in front of 4 and becomes the head, with its prev null.
Example 2
Input: head = [], values = [8, -3, 0]
[0,-3,8]Explanation: The list is empty, so the node for 8 is the whole list at first. The node for -3 goes in front of it, and then the node for 0 goes in front of -3.
Example 3
Input: head = [-1000000000], values = [11]
[11,-1000000000]Check your understanding
Work out the answer for this input before you write any code.
Constraints
0 ≤ number of nodes ≤ 1051 ≤ values.length ≤ 105-109 ≤ Node.val, values[i] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.