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 −
- if node is not null, then
- l := a new set
- temp := node
- insert value of temp into l
- while next of temp is not null, do
- if value of next of temp is not in l, then
- insert value of next of temp into l
- temp := next of temp
- otherwise,
- next of temp := next of next of temp
- if value of next of temp is not in l, then
- return node
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): 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))
Input
[2, 4, 6, 1, 4, 6, 9]
Output
[2, 4, 6, 1, 9, ]