我正在尝试实现一种算法来从链表中删除重复项,但是当我检查当前节点是否有与下一个节点相同的数据时,我的算法会冻结。
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()
这可能真的很傻,但我现在无法发现任何想法?
答案 0 :(得分:2)
在你的while循环中:
{"cost": 500, /* whatever else */
应该是
dryRun=false
否则它只是在每次迭代时保持相同的runner = current.next
,因为它永远不会在循环中更改runner = runner.next
。同样修复了几行。