6 回答

TA貢獻1872條經(jīng)驗 獲得超4個贊
這似乎很可疑:
self.__head = Node(data).get_data()
考慮到您甚至不再引用節(jié)點...然后嘗試調(diào)用 Node 對象的方法。即便如此,您的實現(xiàn)仍然是錯誤的。
我確定還有其他問題,但你可以谷歌這個或?qū)嶋H做你自己的項目/家庭作業(yè)。

TA貢獻1816條經(jīng)驗 獲得超6個贊
所以,我已經(jīng)為我的問題找到了答案。謝謝大家的幫助。這個我還不是很清楚:
我知道與 Java 等語言相比,python 默認不帶有私有變量,但我相信 python 是關(guān)于尊重約定的,而“__”是告訴另一個開發(fā)人員這個特定實體是私有的約定。
但是,在我的情況下,我將無法直接訪問 Node 類表單 LinkedList 類的數(shù)據(jù)和下一個屬性,反之亦然,因為在使用私有變量時,名稱會解析為_Classnmae__attribute_name。所以更好的解決方案是使用 getter 和 setter,因為它們是通用的。
def add(self,data):
#Remove pass and write the logic to add an element
new_node = Node(data)
if self.__head is None:
self.__head = self.__tail = new_node
else:
self.__tail.set_next(new_node)
self.__tail = new_node
def display(self):
#Remove pass and write the logic to display the elements
temp = self.__head
msg = []
c = Node(temp)
while (temp is not None):
msg.append(str(temp.get_data()))
temp = temp.get_next()
msg = ' '.join(msg)
print(msg)
算法:
添加(數(shù)據(jù))
用數(shù)據(jù)創(chuàng)建一個新節(jié)點
如果鏈表為空(頭節(jié)點不引用任何其他節(jié)點),則使頭節(jié)點和尾節(jié)點引用新節(jié)點
除此以外,
一種。使尾節(jié)點的鏈接指向新節(jié)點
灣 將新節(jié)點稱為尾節(jié)點

TA貢獻1757條經(jīng)驗 獲得超7個贊
這是一種通過使用我知道的幾個單鏈表實現(xiàn)“技巧”來更簡潔地做到這一點的方法。
鏈表總是由至少一個自動創(chuàng)建并存儲在實例屬性中的哨兵節(jié)點組成self._tail
。擁有它有幾個好處。
知道在哪里
tail
可以快速輕松地添加一些東西。該列表永遠不會為空,因此無需檢查特殊情況。這樣做的一個很好的副作用意味著迭代列表的元素只需要跟隨
self._next
直到它是哨兵節(jié)點——一個單一的條件表達式。
另一個“技巧”是在當(dāng)前哨兵節(jié)點之前添加一個新的最后一個元素——這在單鏈表中聽起來很慢,因為它似乎需要修改Node
要添加的元素。為了達到這樣做的效果,但避免實際這樣做,它所做的是將現(xiàn)有的哨兵節(jié)點轉(zhuǎn)換為新的哨兵節(jié)點Node
,并將其_next
屬性設(shè)為它創(chuàng)建的新哨兵節(jié)點,以替換之前被重用的哨兵節(jié)點。
這如何有助于理解以下代碼中發(fā)生的事情:
class LinkedList:
def __init__(self):
self._tail = Node()
self._head = self._tail
def add(self, data):
""" Add an item to the end of the linked list. """
new_tail = Node()
self._tail.set_data(data) # Convert existing tail into a data node.
self._tail.set_next(new_tail)
self._tail = new_tail
print('adding:', data)
def display(self):
""" Traverse linked list and print data associated with each Node. """
print('\nLinked list contents:')
curr = self._head
while curr is not self._tail:
print(' ' + curr.get_data())
curr = curr.get_next()
class Node:
def __init__(self, data=None):
self._data = data
self._next = None
def get_data(self):
return self._data
def set_data(self, data):
self._data = data
def get_next(self):
return self._next
def set_next(self, next_node):
self._next = next_node
if __name__ == '__main__':
list1 = LinkedList()
list1.add("Sugar")
list1.add("Milk")
list1.add("Tea")
list1.add("Biscuits")
list1.display()
輸出:
adding: Sugar
adding: Milk
adding: Tea
adding: Biscuits
Linked list contents:
Sugar
Milk
Tea
Biscuits
添加回答
舉報