oneby7

Linked Lists Singly linked list basics

272. Delete Node in a Linked List

Medium

A singly 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, and it has no way to reach the nodes before the given one. The given node is never the last node of the list.

Deleting the node here 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. Your function returns nothing. After it runs, the list is read from its first node, 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 node as the value the node to delete holds. Your function never sees head or this array.

Example 1

head
14-63259
output
14-6259

Input: head = [14, -6, 3, 25, 9], node = 3

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

Explanation: The node to delete holds 3, in the middle of the list. Afterwards 3 is gone, the list has four nodes, and -6 is followed by 25.

Example 2

1020
head
20
output

Input: head = [10, 20], node = 10

Output: [20]

Explanation: The node to delete is the first node. Only 20 is left, and the list is still read from its first node.

Example 3

6-10-7
head
6-1-7
output

Input: head = [6, -1, 0, -7], node = 0

Output: [6,-1,-7]

Explanation: The node holding 0 is the second to last node. After the deletion, -1 is followed by -7, which is still the last value.

Check your understanding

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

head = [8, -3, 6, 2, 11], node = 6

Constraints

  • 2 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109
  • All the values in the list are distinct.
  • The node to delete is a node of the list, and it is not 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.