Suppose we have a linked list of numbers, we have to remove those numbers which appear multiple times in the linked list (hold only one occurrence in the output), we also have to maintain the order of the appearance in the original linked list.
So, if the input is like [2 -> 4 -> 6 -> 1 -> 4 -> 6 -> 9], then the output will be [2 -> 4 -> 6 -> 1 -> 9].
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[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): if node: l = set() temp = node l.add(temp.val) while temp.next: if temp.next.val not in l: l.add(temp.next.val) temp = temp.next else: temp.next = temp.next.next return node ob = Solution() head = make_list([2, 4, 6, 1, 4, 6, 9]) print_list(ob.solve(head))
[2, 4, 6, 1, 4, 6, 9]
[2, 4, 6, 1, 9, ]