Remove Linked List Elements - Problem
You're given the head of a linked list and an integer val. Your task is to remove all nodes from the linked list that contain the value val, and return the new head of the modified list.

This is a classic linked list manipulation problem that tests your understanding of pointer management and edge case handling. You'll need to consider scenarios like removing the head node, removing consecutive nodes, or even removing all nodes from the list.

Key Challenge: The tricky part is handling cases where the head node itself needs to be removed, which requires careful pointer manipulation to avoid losing the reference to the new list.

Input & Output

example_1.py — Remove Middle Elements
$ Input: head = [1,2,6,3,4,5,6], val = 6
Output: [1,2,3,4,5]
💡 Note: The nodes with value 6 are at positions 2 and 6 (0-indexed). After removing these nodes, the remaining list becomes [1,2,3,4,5].
example_2.py — Empty List
$ Input: head = [], val = 1
Output: []
💡 Note: The input list is already empty, so removing any value results in an empty list.
example_3.py — Remove All Elements
$ Input: head = [7,7,7,7], val = 7
Output: []
💡 Note: All nodes in the list have the value 7, so removing all occurrences of 7 results in an empty list.

Constraints

  • The number of nodes in the list is in the range [0, 104]
  • -50 ≤ Node.val ≤ 50
  • 0 ≤ val ≤ 50

Visualization

Tap to expand
Remove Linked List Elements INPUT Linked List (val = 6): 1 2 6 3 4 5 6 NULL = Remove (val=6) Input Parameters: head = [1,2,6,3,4,5,6] val = 6 Use dummy node for edge case handling ALGORITHM STEPS 1 Create Dummy Node dummy.next = head Handles head removal 2 Initialize Pointer prev = dummy curr = head 3 Traverse List If curr.val == val: prev.next = curr.next Else: prev = curr 4 Return Result return dummy.next New head of list Complexity: Time: O(n) Space: O(1) FINAL RESULT Modified Linked List: 1 2 3 4 5 NULL Nodes with value 6 removed: 6 6 Output: [1, 2, 3, 4, 5] OK - Complete Key Insight: Using a dummy node before the head simplifies edge cases where the head itself needs removal. This technique avoids special case handling and makes the code cleaner. The dummy node acts as a sentinel that always stays, so we just return dummy.next as the new head after processing. TutorialsPoint - Remove Linked List Elements | Optimal Solution (Dummy Node Approach)
Asked in
Amazon 45 Microsoft 32 Google 28 Meta 22
82.2K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen