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 −
Let us see the following implementation to get better understanding −
class ListNode: def __init__(self, data, next = None): self.val = data self.next = next def make_list(elements): head = ListNode(elements) 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)
[5, 8, 6, 5, 9, 6, 4, ]