oneby7

Linked Lists Doubly linked lists

282. Delete the K-th Node of a Doubly Linked List

Medium

You are given head, the first node of a doubly linked list, and an integer k. Delete the k-th node of the list, counting from the head, and return the head of the list that is left.

Positions start at 1: the head is node 1, the node after it is node 2, and so on. So k = 1 deletes the head, and k equal to the number of nodes deletes the last node.

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 deletion, both directions must still 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, and the output shows the list you return the same way. When no nodes are left, return null, which shows as []. 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 = [14, -6, 22, 3, 9], k = 3

Output: [14,-6,3,9]

Explanation: Node 3 holds 22. After the deletion, the node holding -6 points forward to the node holding 3, and the node holding 3 points back to the node holding -6.

Example 2

Input: head = [5, 8, 5, 2], k = 1

Output: [8,5,2]

Explanation: Node 1 is the head. Once it is deleted, the node holding 8 is the head to return, and its prev is null.

Example 3

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

Output: [7,-1000000000]

Explanation: Node 3 is the last node. The node holding -1000000000 becomes the last node, and its next is null.

Check your understanding

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

head = [3, 9, 3, 5, 1], k = 4

Constraints

  • 1 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 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.