簡體   English   中英

python中的循環鏈表

[英]circularly linked list in python

我被困在python中實現循環鏈​​接列表的添加功能。 我有一個應該指向節點的頭指針,但是每次向列表中添加內容時,頭始終為None。 這是我到目前為止的代碼:

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)

您只能在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

容易修復! 在您的add函數中,您將新的head分配給head變量-限於該函數的范圍,並且在返回時將消失!

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

編輯:當您分配head = self.head您使它們都指向同一對象。 但是它們是單獨的引用:無論它們碰巧引用相同的事物,改變一個不會改變另一個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM