oneby7

Linked Lists Singly linked list basics

271. Delete the Node with Value X

Medium

You are given head, the first node of a singly linked list, and an integer x. Remove the first node that holds the value x, the one closest to the head, and return the head of the list that is left. The other nodes stay in their order. If no node holds x, return the list unchanged.

A singly linked list is a chain of nodes. Each node holds a value and a pointer to the next node, and the last node's pointer is null. An empty list has no nodes, and its head is null.

The examples write a list as its values from the head on, so head = [4,1,6] is the list 4 → 1 → 6. The output shows the list from the node you return, and shows an empty list as [].

Example 1

head
8-35-312
output
85-312

Input: head = [8, -3, 5, -3, 12], x = -3

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

Explanation: The value -3 sits in the second and the fourth node. Only the second node is removed, so 8 now points to 5. The later -3 stays.

Example 2

629
head
29
output

Input: head = [6, 2, 9], x = 6

Output: [2,9]

Explanation: The head holds 6, so the head is removed. The node holding 2 is the new head.

Example 3

471
head
471
output

Input: head = [4, 7, 1], x = 5

Output: [4,7,1]

Explanation: No node holds 5, so the list comes back as it was.

Check your understanding

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

head = [2, 7, 4, 7, 1], x = 7

Constraints

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