oneby7

Linked Lists Doubly linked lists

283. Delete a Given Node of a Doubly Linked List

Medium

A doubly linked list has one node you must delete. Your function is given that node, and only that node. It does not get the head of the list. The given node is never the head, but it can be 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. The comment at the top of the starter code shows the node in your language.

Deleting the node means three things: its value is no longer in the list, the list has one node fewer, and every other value keeps its place in the order. Both directions must stay right afterwards. Your function returns nothing. After it runs, the list is read from its head, and that is the output.

The examples write a list as its values from the head on, so head = [4,1,6] is the list 4 ⇄ 1 ⇄ 6. They write position as the place of the node to delete, counting the head as 1. Your function never sees head or position, only the node. 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 = [8, -3, 21, 5, 13], position = 3

Output: [8,-3,5,13]

Explanation: Node 3 holds 21. Afterwards the node holding -3 points forward to 5, and the node holding 5 points back to -3.

Example 2

Input: head = [40, 7, -16], position = 3

Output: [40,7]

Explanation: The node to delete is the last node. The node holding 7 becomes the last node, so its next is now null.

Example 3

Input: head = [-5, 0, -5, 0], position = 2

Output: [-5,-5,0]

Explanation: Values can repeat. The node is chosen by its place, so the 0 in node 2 goes and the 0 in node 4 stays.

Check your understanding

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

head = [3, 10, -4, 7], position = 2

Constraints

  • 2 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • 2 ≤ position ≤ number of nodes
  • The node to delete is never the head. It can be the last node.

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.