oneby7

Linked Lists Singly linked list basics

273. Remove Linked List Elements

Easy

You are given head, the first node of a singly linked list, and an integer val. Remove every node whose value equals val, and return the head of the list that is left. The other nodes stay in their order. If no node holds val, return the list unchanged. If every node holds it, return the empty list.

Delete the Node with Value X removes only the first match. Here every match goes.

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
177375
output
135

Input: head = [1, 7, 7, 3, 7, 5], val = 7

Output: [1,3,5]

Explanation: The value 7 sits in the second, third and fifth node. All three go, including the two that sit next to each other. The nodes holding 1, 3 and 5 stay in their order.

Example 2

-4-410-4
head
10
output

Input: head = [-4, -4, 10, -4], val = -4

Output: [10]

Explanation: The first two nodes both hold -4, so the head goes and so does the node after it. The node holding 10 becomes the new head, and the last node goes too.

Example 3

999

Input: head = [9, 9, 9], val = 9

Output: []

Explanation: Every node holds 9, so nothing is left and the answer is the empty list.

Check your understanding

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

head = [3, 5, 5, 8, 5], val = 5

Constraints

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