[英]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.