我正在运行下面的代码,以从链接列表中删除重复项。但是我的代码仅在删除重复项之前打印链接列表。一旦调用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
子句中。由于每次更新
current
后second
和current
始终以相同的值开头,因此我更改了在单个语句中分配它们两者的逻辑。原来的方式会很好用,我只是认为这种方式看起来更好。
关于python-2.7 - 从链接列表Python删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42728271/