[英]Removing a node in a Linked List using Links
我想創建一個刪除節點功能,以刪除我在python中LinkedList的計數所給定位置的節點。 我知道python有一個內置的垃圾清除器,所以我的代碼看起來像這樣嗎?
def removeItem(self,position):
# ListNode is a seperate file I referenced which creates a node with data and a link.
node = ListNode.item
count = 0
while count != position:
node.link = node.link.link
count +=1
#Node.Link should link to the next node in the sequence.
return node
刪除節點的最簡單方法是創建對currentNode
和previousNode
的引用,如下所示。
def removeItem(self,position):
currentNode = ListNode
previousNode = None
count = 0
while count != position:
#quick check to make sure next node is not empty
if currentNode.link == None:
print("Position Invalid")
return None
previousNode = currentNode
currentNode = currentNode.link
count +=1
#Node.Link should link to the next node in the sequence.
previousNode.link = currentNode.link
return currentNode
基本上, previousNode.link = currentNode.link
使用的是previousNode的下一個鏈接來引用currentNode的下一個鏈接,因此currentNode(您要刪除的節點[中間的節點])將丟失引用,並最終被垃圾回收集電極。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.