我正在嘗試在 Python 中創建一個包含各種方法的鏈表。對于插入,我有三種方法,add_at_beginning、add_at_position & add_at_end
節點類:
class Node:
def __init__(self, data):
self.data = data
self.next = None
下面是我的鏈表。
class LinkedList:
def __init__(self):
self.head = None
def add_at_beginning(self, data):
temp = Node(data)
if self.head is None:
self.head = temp
else:
temp.next = self.head
self.head = temp
def add_at_end(self, data):
temp = Node(data)
if self.head.next is None:
self.head = temp
else:
while self.head.next is not None:
self.head = self.head.next
self.head.next = temp
def add_at_position(self, data, pos):
temp = Node(data)
if self.head is None:
self.head = temp
else:
curr = self.head
i = 1
while i < pos-1:
curr = curr.next
i = 1
temp.next = curr.next
curr.next = temp
def traverse_linked_list(self):
if self.head is None:
print('Empty LinkedList')
else:
curr = self.head
while curr.next is not None:
print(curr.data)
curr = curr.next
我面臨的問題是add_at_end
這是我的插入順序。
if __name__ == '__main__':
ll = LinkedList()
ll.head = Node(1)
ll.add_at_beginning(4)
ll.add_at_beginning(3)
ll.add_at_beginning(2)
ll.add_at_position(5, 2)
ll.traverse_linked_list()
結果:2, 5, 3,4
但是如果我通過呼叫在最后添加一個元素add_at_end,它會洗掉鏈表中的每個元素。插入順序:
ll = LinkedList()
ll.head = Node(1)
ll.add_at_beginning(4)
ll.add_at_beginning(3)
ll.add_at_beginning(2)
ll.add_at_position(5, 2)
ll.add_at_end(10)
ll.traverse_linked_list()
結果:1
在方法中:add_at_end我一直遍歷到linkedlist的末尾并檢查head.next是否為NONE,然后我才將我的temp節點分配給self.head.next但是當我在最初添加元素后遍歷串列時輸出完全錯誤。
誰能讓我知道我在這里犯了什么錯誤,我該如何解決?
uj5u.com熱心網友回復:
我看到兩個更正:
一)add_at_end:
不要改變self.head。而是使用您在其他方法中使用的 curr 之類的虛擬物件。改變self.head會產生不可預測的結果。它應該始終指向鏈表的頭部。所以初始化一個curr變數指向你的頭部,然后遍歷到最后,然后temp將next.
更改如下:
def add_at_end(self, data):
temp = Node(data)
if self.head is None:
self.head = temp
return
curr = self.head
while curr.next is not None:
curr = curr.next
curr.next = temp
b)當您遍歷鏈表進行列印時,您需要檢查if curr is not Nonewhile loop not curr.next is not None,您在列印前檢查當前節點而不是下一個節點。
def traverse_linked_list(self):
if self.head is None:
print('Empty LinkedList')
else:
curr = self.head
while curr is not None:
print(curr.data)
curr = curr.next
uj5u.com熱心網友回復:
最簡單的做法可能是設定一個變數來幫助您走到盡頭,這樣您就不會在找到盡頭時更改串列:
position = self.head.next
while position.next is not None:
position = position.next
position.next = temp
uj5u.com熱心網友回復:
每次執行時head = head.next,都會從串列中洗掉一個節點,從第一個節點一直到最后一個節點,然后添加新的(現在也是唯一的)節點。這就是你得到這個結果的原因。其他答案已經解釋了如何解決。
建議:如果你要在兩邊追加,為什么不同時保留“ LinkedList.tail”和“ Node.previous”指標?
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/466279.html
