oneby7

Linked Lists Doubly linked lists

278. Insert Before the K-th Node

Medium

You are given head, the first node of a doubly linked list, and two integers k and value. Insert a new node holding value just before the k-th node of the list. Return the head of the list after the insertion.

Positions count from 1, so the head is node 1. k = 1 puts the new node in front of the head, and the new node becomes the head. k is at most the number of nodes, so node k always exists, and the new node always has a node after it. The nodes already in the list keep their order.

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. The insert must keep both directions 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, 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 = [12, -5, 30, 8], k = 3, value = 41

Output: [12,-5,41,30,8]

Explanation: Node 3 holds 30, so the new node goes between -5 and 30. Its prev points to -5 and its next to 30. The node holding -5 now points forward to it, and the node holding 30 points back to it.

Example 2

Input: head = [4, 9], k = 1, value = -6

Output: [-6,4,9]

Explanation: With k = 1 the new node goes in front of 4 and becomes the head, with its prev null. The node holding 4 now points back to it.

Example 3

Input: head = [0, -3, 7], k = 3, value = -1000000000

Output: [0,-3,-1000000000,7]

Explanation: Node 3 is the last node, so the new node goes just before it, and 7 stays last.

Check your understanding

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

head = [7, 1, 8, 2], k = 3, value = 5

Constraints

  • 1 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val, value ≤ 109
  • 1 ≤ k ≤ number of nodes

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.