मान लीजिए हमारे पास संख्याओं की एक लिंक्ड लिस्ट है, हमें उन संख्याओं को हटाना है जो लिंक्ड लिस्ट में कई बार दिखाई देती हैं (आउटपुट में केवल एक घटना रखें), हमें मूल लिंक्ड लिस्ट में उपस्थिति के क्रम को भी बनाए रखना है।
इसलिए, यदि इनपुट [2 -> 4 -> 6 -> 1 -> 4 -> 6 -> 9] जैसा है, तो आउटपुट [2 -> 4 -> 6 -> 1 -> 9] होगा।
इसे हल करने के लिए, हम इन चरणों का पालन करेंगे −
- यदि node null नहीं है, तो
- l := एक नया सेट
- temp := node
- temp के मान को l में डालें
- जब तक temp का next null नहीं है, करें
- यदि temp के next का मान l में नहीं है, तो
- temp के next के मान को l में डालें
- temp := temp का next
- अन्यथा,
- temp का next := temp के next का next
- यदि temp के next का मान l में नहीं है, तो
- node वापस करें
बेहतर समझ के लिए निम्नलिखित कार्यान्वयन देखें −
उदाहरण
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, ]