Program to remove all nodes of a linked list whose value is same as in Python

A singly linked list is a linear data structure where each node contains data and a reference to the next node. Sometimes we need to remove all nodes with a specific target value while maintaining the list structure.

So, if the input is like [5,8,2,6,5,2,9,6,2,4] and target is 2, then the output will be [5, 8, 6, 5, 9, 6, 4].

Algorithm

To solve this problem, we follow these steps ?

  • Start with the head node
  • While current node and next node exist:
    • If next node's value equals target, skip it by updating the link
    • Move to the next node
  • Handle the special case where head node itself needs to be removed
  • Return the updated head

Implementation

ListNode Class and Helper Functions

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

def make_list(elements):
    if not elements:
        return None
    head = ListNode(elements[0])
    ptr = head
    for element in elements[1:]:
        ptr.next = ListNode(element)
        ptr = ptr.next
    return head

def print_list(head):
    result = []
    ptr = head
    while ptr:
        result.append(ptr.val)
        ptr = ptr.next
    print(result)

Solution

class Solution:
    def solve(self, node, target):
        if not node:
            return None
        
        head = node
        
        # Remove nodes from middle and end
        while node and node.next:
            if node.next.val == target:
                node.next = node.next.next
            else:
                node = node.next
        
        # Handle head node removal
        if head.val == target:
            return head.next
        else:
            return head

# Example usage
ob = Solution()
head = make_list([5, 8, 2, 6, 5, 2, 9, 6, 2, 4])
print("Original list:")
print_list(head)

new_head = ob.solve(head, 2)
print("After removing nodes with value 2:")
print_list(new_head)
Original list:
[5, 8, 2, 6, 5, 2, 9, 6, 2, 4]
After removing nodes with value 2:
[5, 8, 6, 5, 9, 6, 4]

How It Works

The algorithm works in two phases:

  • Phase 1: Traverse the list and remove all target nodes except potentially the head
  • Phase 2: Check if the head node itself needs to be removed

The key insight is to modify the next pointers to skip over nodes with target values, effectively removing them from the linked list.

Time and Space Complexity

  • Time Complexity: O(n) where n is the number of nodes
  • Space Complexity: O(1) as we only use constant extra space

Conclusion

This solution efficiently removes all nodes with a target value by updating pointer references. The algorithm handles both middle nodes and the special case of head node removal in a single pass.

Updated on: 2026-03-25T10:50:14+05:30

469 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements