我正在尝试编写一个片段,用于删除python中链表中的重复元素。
我在字典中检查先前节点值的条件不是正确的。我无法弄清楚为什么它总是返回false。
节点值为[0-> 1-> 2-> 2-> 3-> 4-> 4-> 5
def RemoveRepeatNode(self):
curr_node = self.head
unique_list = {}
unique_list[curr_node.data] = 1
while(curr_node.next != None):
if curr_node.next.data in unique_list: ## doesn't evaluate to True
print "repeated values ", curr_node.next.data
curr_node = curr_node.next.next
else:
unique_list[curr_node.data] = 1
curr_node = curr_node.next
答案 0 :(得分:1)
您的if子句可能没问题,但您不会重新链接。变化:
def RemoveRepeatNode(self):
curr_node = self.head
unique = {curr_node.data} # better data structure: set
while(curr_node.next != None):
if curr_node.next.data in unique:
curr_node.next = curr_node.next.next
# ^^^^^ relink!
else:
unique.add(curr_node.next.data)
# add .next.data ^^^^^ that's the one you checked
curr_node = curr_node.next