Program to remove last occurrence of a given target from a linked list in Python


Suppose we have a singly linked list, and another value called target, we have to remove the last occurrence of target in the given list.

So, if the input is like [5,4,2,6,5,2,3,2,4,5,4,7], target = 5, then the output will be [5, 4, 2, 6, 5, 2, 3, 2, 4, 4, 7, ]

To solve this, we will follow these steps −

  • head := node
  • k := null, prev := null
  • found := False
  • while node is not null, do
    • if value of node is same as target, then
      • found := True
      • prev := k
    • k := node
    • node := next of node
  • if found is False, then
    • return head
  • if prev is null, then
    • return next of head
  • nect of prev := next of the next of prev
  • return head

Let us see the following implementation to get better understanding −

Example

 Live Demo

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
      k = None
      prev = None
      found = False
      while node:
         if node.val == target:
            found = True
         prev = k
         k = node
         node = node.next
         if found == False:
            return head
         if not prev:
            return head.next
            prev.next = prev.next.next
      return head
ob = Solution()
L = make_list([5,4,2,6,5,2,3,2,4,5,4,7])
target = 5
print_list(ob.solve(L, target))

Input

[5,4,2,6,5,2,3,2,4,5,4,7]

Output

[5, 4, 2, 6, 5, 2, 3, 2, 4, 4, 7, ]

Updated on: 19-Nov-2020

273 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements