oneby7

Linked Lists Doubly linked lists

277. Insert Before the Tail

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 tail: a new node holding the value goes just in front of the last node of the list. 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.

The node that was last at the start stays last, because every new node goes in front of it. So the inserted values end up in their given order, just before that node. The list always has at least one node. When it has exactly one, that node is both the head and the tail, so the first new node goes in front of it and becomes the head.

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 = [3, 8, -5, 12], values = [6, -1]

Output: [3,8,-5,6,-1,12]

Explanation: The node for 6 goes between -5 and the tail, 12. The tail is still 12, so the node for -1 goes between 6 and 12.

Example 2

Input: head = [9], values = [4, 7]

Output: [4,7,9]

Explanation: The only node, 9, is the tail. The node for 4 goes in front of it and becomes the head. Then the node for 7 goes between 4 and 9.

Example 3

Input: head = [1000000000, -1000000000], values = [0]

Output: [1000000000,0,-1000000000]

Check your understanding

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

head = [5, 2, 8], values = [1, 4, 6]

Constraints

  • 1 ≤ 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.