321. Remove All Occurrences of a Given Value

EasyLinked ListLinked ListDeletionPointer Manipulation

Given the head of a singly linked list and an integer val, remove all nodes whose value equals val and return the new head.

Use a dummy node to handle head deletions cleanly.

Input: Head of a singly linked list and integer val.

Output: Head of the updated linked list with all matching nodes removed.

Examples

Example 1
Input: [1,2,6,3,4,5,6], 6
Output: [1,2,3,4,5]
Explanation: Remove both 6s. Result: 1→2→3→4→5.
Example 2
Input: [7,7,7,7], 7
Output: []
Explanation: All nodes removed. Return NULL.
Example 3
Input: [1,2,3], 4
Output: [1,2,3]
Explanation: Val 4 not found. Return list unchanged.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →