Pages

106 Remove Linked List Elements - delete all nodes with a given value

 

Problem Statement

Given the head of a singly linked list and an integer val,
remove all nodes from the list that have val as their value.

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

Example 2:

Input: head = [], val = 1
Output: []

Example 3:

Input: head = [7,7,7,7], val = 7
Output: []

Constraints:

  • The number of nodes in the list is in the range [0, 104].
  • 1 <= Node.val <= 50
  • 0 <= val <= 50

Approach

We’ll use a dummy node to simplify edge cases (like deleting the head itself).
Then, we’ll iterate through the list and skip any node whose value is equal to val.

Steps

  1. Create a dummy node pointing to the head.

  2. Initialize a pointer current = dummy.

  3. While current.next is not None:

    • If current.next.val == val, remove it:
      current.next = current.next.next

    • Else, move to next node: current = current.next

  4. Return dummy.next (new head).




class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def removeElements(head: ListNode, val: int) -> ListNode:
    dummy = ListNode(0)
    dummy.next = head
    current = dummy

    while current.next:
        if current.next.val == val:
            current.next = current.next.next  # skip the node
        else:
            current = current.next

    return dummy.next