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


Suppose we have a singly linked list, and one target, we have to return the same linked after deleting all nodes whose value is same as target.

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

To solve this, we will follow these steps −

  • head := node
  • while node and node.next are not null, do
    • while value of next of node is same as target, do
      • next of node := next of next of node
    • node := next of node
  • if value of head is same as target, then
    • return next of head
  • otherwise,
    • return head

Let us see the following implementation to get better understanding −

Example

class ListNode:
   def __init__(self, data, next = None):
      self.val = data
      self.next = next
def make_list(elements):
   head = ListNode(elements[0])
   for element in elements[1:]:
      ptr = head
   while ptr.next:
      ptr = ptr.next
      ptr.next = ListNode(element)
   return head
def print_list(head):
   ptr = head
   print('[', end = "")
   while ptr:
      print(ptr.val, end = ", ")
      ptr = ptr.next
      print(']')
class Solution:
   def solve(self, node, target):
      head = node
      while (node and node.next):
         while node.next.val == target:
            node.next = node.next.next
            node = node.next
         if head.val == target:
            return head.next
         else:
      return head
ob = Solution()
head = make_list([5,8,2,6,5,2,9,6,2,4])
ob.solve(head, 2)
print_list(head)

Input

[5,8,2,6,5,2,9,6,2,4]

Output

[5, 8, 6, 5, 9, 6, 4, ]

Updated on: 06-Oct-2020

291 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements