All problems

Remove Linked List Elements

Easy · linked list

You are given the head of a singly linked list and an integer val. Delete every node whose value equals val, and return the head of the resulting list.

The nodes that remain keep their original order. If every node is deleted, or the list was empty to begin with, return an empty list. The nodes you receive are ListNode objects with a val and a next.

Examples

Example 1

Input: head = [4, 1, 4, 2, 4, 3], val = 4

Output: [1, 2, 3]

All three nodes holding 4 are removed, including the first one.

Example 2

Input: head = [5, 6, 7], val = 9

Output: [5, 6, 7]

No node holds 9, so the list is unchanged.

Example 3

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

Output: []

Constraints