2017-10-18 88 views
0

我想寫一個代碼片段來刪除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 

回答

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 
+0

瞭解它..非常感謝糾正錯誤的邏輯部分。 – oneday

相關問題