簡體   English   中英

Python 有序鏈表與引用正確名稱混淆

[英]Python Ordered linked list confusion with referencing the right name

所以我關注這個鏈表,它是一個有序鏈表。 以下是代碼供參考:

class Node:
    def __init__(self,initdata):
        self.data = initdata
        self.next = None

    def getData(self):
        return self.data

    def getNext(self):
        return self.next

    def setData(self,newdata):
        self.data = newdata

    def setNext(self,newnext):
        self.next = newnext

class OrderedList:
    def __init__(self):
        self.head = None

    def add(self,item):
        current = self.head
        previous = None
        stop = False
        while current != None and not stop:
            if current.getData() > item:
                stop = True
            else:
                previous = current
                current = current.getNext()

        temp = Node(item)
        if previous == None:
            temp.setNext(self.head)
            self.head = temp
        else:
            temp.setNext(current)
            previous.setNext(temp)

    def isEmpty(self):
        return self.head == None

    def size(self):
        current = self.head
        count = 0
        while current != None:
            count = count + 1
            current = current.getNext()

        return count


mylist = OrderedList()
mylist.add(31)
mylist.add(77)
mylist.add(17)
mylist.add(93)
mylist.add(26)
mylist.add(54)

print(mylist.size())

如您所見,調用mylist.size()時,它將返回 6 的大小,因為添加了 6 個東西。 但在 add 方法中,特別是以下行:

if previous == None:
            temp.setNext(self.head)
            self.head = temp

如果我將self.head = temp更改為current = temp ,它將返回大小為 0。這意味着沒有引用數字的 rest。 但是為什么會這樣呢,我想既然我們之前定義了current = self.head ,那么將self.head = temp更改為current = temp會產生相同的結果嗎?

current = self.head
current = temp

上面的第一行將使current引用self.head所指的任何內容。 第二行使current引用temp ,但它也不使self.head引用temp

您可以將current視為對某些底層 object 的引用(它也恰好被self.head引用)。 current重新分配給temp不會改變self.head所指的內容。

在使用 Python 時,這可能是一個常見的混淆,並且有更多關於對象和名稱處理方式的信息。 參見例如Python 變量引用賦值

暫無
暫無

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

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