Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 检查字典中是否存在节点值_Python_Dictionary_Linked List - Fatal编程技术网

Python 检查字典中是否存在节点值

Python 检查字典中是否存在节点值,python,dictionary,linked-list,Python,Dictionary,Linked List,我试图编写一个代码片段,用于在python中删除链表中的重复元素 我检查字典中以前的节点值的条件不是true。我不明白为什么它总是返回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):

我试图编写一个代码片段,用于在python中删除链表中的重复元素

我检查字典中以前的节点值的条件不是true。我不明白为什么它总是返回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

您的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

明白了。非常感谢你也纠正了错误的逻辑部分。