oneby7

Linked Lists Doubly linked lists

276. Insert Before the Head

Medium

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]

Output: [-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]

Output: [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]

Output: [11,-1000000000]

Check your understanding

Work out the answer for this input before you write any code.

head = [6, 2], values = [9, 4, 1]

Constraints

  • 0 ≤ number of nodes ≤ 105
  • 1 ≤ values.length ≤ 105
  • -109 ≤ Node.val, values[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.