2010-12-05 78 views
1

我被困在python中實現了循環鏈表的add函數。我有一個頭指針應該是一個節點的引用,但是每次我向列表中添加一些東西時,頭總是無。下面是代碼我迄今:python中的循環鏈表

class CircleList(): 

    __slots__ = ('head', 'size') 

    def __init__(self): 
     self.head = None 
     self.size = 0 

    def __str__(self): 
     result = "<" 
     node = self.head 
     count = self.size 
     while count != 0: 
      result = result + str(node.data) 
      if count != 1: 
       result = result + ", " 
      node = node.next 
      count -= 1 
     result = result + ">" 
     return result 

    def add(self, element): 
     head = self.head 
     print(head) 
     size = self.size 
     if head == None: 
      head = Node(element, None) 
      head.next = head 
     else: 
      cursor = head 
      while cursor.next != head: 
       cursor = cursor.next 
      temp = Node(element, head) 
      cursor.next = temp 
     size += 1 


class Node(): 
    __slots__ = ('data','next') 

    def __init__(self, data, next): 
     self.data = data 
     self.next = next 

這裏是驅動程序:

stream = open('data.txt', 'r') 

circlelist = CircleList() 

for name in stream 
    circlelist.add(name) 

print(circlelist) 
+1

爲什麼你實現它這樣的原因嗎?它不完全是pythonic,你可以輕鬆想出一個更加優雅的版本來擴展`list`,提供像`__getitem__`這樣的元方法並使用索引。這也消除了對多餘的Node類的需求。另外,我建議堅持列表中衆所周知的界面。 – 2010-12-05 17:23:37

回答

1

您只在add()方法中將新節點分配給您當地的head變量,而不是實際的CircleList實例成員。

你可能想要做這樣的事情:

def add(self, element): 
    head = self.head 
    print(head) 
    size = self.size 
    if head is None: 
     self.head = head = Node(element, None) # Also set the instance member. 
     head.next = head 
0

容易解決!在你的增加功能中,你將新的頭部分配給head變量 - 這個變量被限制在函數的範圍內,並且在它返回時消失!

您必須設置self.head的值,即當前實例的屬性。

編輯:當你分配head = self.head你讓他們都指向同一個對象。但它們是單獨的參考文獻:它們是否碰巧提及相同的事物,改變一個不會改變另一個。