简体   繁体   中英

Remove Duplicates from unsorted Linked list(python)

In my last code for removing duplicates, the method removeDup isn't working. The last print(ll.display()) is printing the previous linked list. I was hoping it to print only unique nodes. What am I missing in removeDups method? I can't figure out. What is happening in the code here?

class Node:
    def __init__(self,data = None):
        self.data = data
        self.next = None

    def __repr__(self):
        return self.data

class LList:
    def __init__(self):
        self.head = None

    def display(self):
        current = self.head
        node = []

        while current != None:
            node.append(current.data)
            current = current.next
        return node

    def append(self, data):
        elem = Node(data)
        if self.head == None:
            self.head = elem
        else:
            current = self.head
            while current.next != None:
                current = current.next
            current.next = elem

    def add_atFront(self, data):
        elem = Node(data)
        if self.head == None:
            self.head = elem
        else:
            elem.next = self.head
            self.head = elem



    def removeDup(self):
        current = self.head
        previous = None
        elems = []
        while current != None:
            if current.data in elems:
                previous.next= current.next
            else:
                elems.append(current.data)
                previous = current
            current = current.next

ll= LList()
print(ll.display())
ll.append(65)
ll.append(7)
ll.add_atFront('65')
ll.add_atFront('Bare')
ll.insert('10',0)
ll.insert('7',2)
print(ll.display())
ll.removeDup()
print(ll.display())

Your removeDup works fine, the issue is that 65 and '65' are not duplicates, so you should not expect removeDup to dedup them. The same goes for 7 and '7'. Also, note you never defined the insert method, but I'll assume that's just a copy error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM