删除无缓冲区的重复项



我正试图实现一种算法,从linkedlist中删除重复项,但我的算法在检查当前节点是否具有与下一个节点相等的数据时冻结。

class Node:
    def __init__(self, data, next):
        self.data = data
        self.next = next
class LinkedList:
   def __init__(self, head = None):
      self.head = head
   def add(self, item):
      newNode = Node(item, self.head)
      self.head = newNode
   def printit(self):
      current = self.head
      while current is not None:
         print(current.data)
         current = current.next
   def removeDuplicates(self):
      current = self.head
      while current != None:
         runner = current
         while runner.next != None:
            if runner.next.data == current.data:
               runner.next = current.next.next
            else:
               runner = current.next
         current = current.next


mylist = LinkedList()
mylist.add(31)
mylist.add(77)
mylist.add(31)
mylist.add(22)
mylist.add(22)
mylist.add(22)
mylist.printit()
mylist.removeDuplicates()
mylist.printit()

这可能真的很傻,但我现在看不出来,你有什么主意吗?

在while循环中:

runner = current.next
应该

runner = runner.next

否则,它只在每次迭代中取相同的current.next,因为它在循环中从不改变current

相关内容

  • 没有找到相关文章

最新更新