2014-05-13 165 views
0

作爲OOP的第一個項目,我正在研究一個鏈表oop類,得到了大部分的方法,但remove節點方法不起作用。 當我運行代碼,我得到這個錯誤:如何從鏈表中刪除節點?

AttributeError的:「節點」對象有沒有屬性「VAL」

我想不出我在做什麼錯呢!

class Node(): 
    def __init__(self, val): 
     self.value = val 
     self.next = None 


class Linked_list(): 
    def __init__(self): 
     self.next = None 
     nextnode=self.next 


    def insert(self, val, loc): 
     p = self 
     for i in range(0, loc): 
      p = p.next 
     tmp = p.next 
     newNode = Node(val) 
     p.next = newNode 
     newNode.next = tmp 

    def find(self, val): 
     p = self.next 
     # loc = 0  # in case we want to return the location 
     while p != None: 
      if p.value == val: 
       return p 
      else: 
       p = p.next 
       #loc=loc+1 # in case we want to return the location 
     return None 

    def remove_node(self, node): 
     current = self.next 
     previous = None 
     found = False 
     while not found: 
       if current.val == node: 
        found = True 
       else: 
        previous = current 
        current = current.next 

     if previous == None: 
      self.next = current.next 
     else: 
      previous.current.next 



    def __eq__(self, other): 
     cnt=0 
     s=self.next 
     p=other.next 
     if Linked_list.length(self)!=Linked_list.length(other): 
      return False 
     if s.value==p.value: 
      for i in range(Linked_list.length(self)-1): 
       p=p.next 
       s=s.next 
       if s.value==p.value: 
        cnt+=1 
     if cnt==Linked_list.length(self)-1: 
      return True 
     else: 
      return False 

回答

2

Node類在__init__方法分配一個屬性value,但不是一個屬性val,因此錯誤。混淆可能來自您傳遞給__init__的變量被稱爲val