[英]checking node value exists in dictionary
I am trying to write a snippet for removing duplicate elements in a linked list in python. 我正在尝试编写一个片段,以删除python链表中的重复元素。
my condition of checking previous node values in dictionary is not yielding true. 我检查字典中以前的节点值的条件不成立。 I am unable to figure out why it always returns false.
我无法弄清楚为什么它总是返回false。
Node values are [ 0->1->2->2->3->4->4->5 节点值是[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
Your if clause might be fine, but you do not relink. 您的if子句可能很好,但是您不要重新链接。 Change:
更改:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.