python-2.7 - 从链接列表Python删除重复项

标签 python-2.7

我正在运行下面的代码,以从链接列表中删除重复项。但是我的代码仅在删除重复项之前打印链接列表。一旦调用removeDup方法,它就不会打印任何内容。下面是我的代码。请告诉我我想念的是什么。

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

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

    def insert(self, data):
        node = Node(data)
        node.next=self.head
        self.head = node

    def printl(self):
        current  = self.head
        while current:
            print current.data
            current= current.next

    def removeDups(self):
        current = self.head
        while current is not None:
            second = current.next
            while second:
                if second.data == current.data:
                    current.next = second.next.next

                second = second.next
            current = current.next
#        l.printl()


l= LinkedList()
l.insert(15)
l.insert(14)
l.insert(16)
l.insert(15)
l.insert(15)
l.insert(14)
l.insert(18)
l.insert(159)
l.insert(12)
l.insert(10)
l.insert(15)
l.insert(14)

l.printl()
print "==============="

l.removeDups()
l.printl()

最佳答案

您删除发现重复项的逻辑不正确。它使您剪切出一个值的第一个出现与最后一个值之间的所有点之间的所有项。对于您的示例列表,这将导致一个项目,即在重复数据删除运行后打印14(它从第一个值之后切到最后一个值,尽管在此过程中也进行了一些较小的削减)。

这是removeDups方法的固定版本。

def removeDups(self):
    current = second = self.head
    while current is not None:
        while second.next is not None:   # check second.next here rather than second
            if second.next.data == current.data:   # check second.next.data, not second.data
                second.next = second.next.next   # cut second.next out of the list
            else:
                second = second.next   # put this line in an else, to avoid skipping items
        current = second = current.next

主要变化是second指向我们实际感兴趣的第二个节点之前的节点。我们在second.next上完成所有工作。我们需要保留对second的引用,以便我们可以轻松地将second.next从列表中删除。以这种方式执行此操作要求如果切出一个节点,则不要前进second,因此second = second.next行必须位于else子句中。

由于每次更新currentsecondcurrent始终以相同的值开头,因此我更改了在单个语句中分配它们两者的逻辑。原来的方式会很好用,我只是认为这种方式看起来更好。

关于python-2.7 - 从链接列表Python删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42728271/

相关文章:

python-2.7 - PUBSUB CHANNELS 返回空列表

python - 将字典(键和值)写入 csv 文件

python - Python 2.7 的蓝牙?

python - Odoo 可以跟踪计算字段的变化

python - 如何将嵌套列表作为 Python 中的输入

python - 在函数中迭代 Pandas 系列的行

python - 如何通过 http 代理传递所有 Python 的流量?

python - 无法访问 Project Gutenberg 原始文本

python - 如何在不使用 import * 的情况下导入导入其他模块的模块

Python 日志模块在 Mac 上记录,但在 Linux 上不记录