使用链接删除链接列表中的节点
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
是使用前一个节点的下一个 link 来引用当前节点的下一个 link,因此是当前节点(您希望删除的节点 [中间的节点])将丢失引用并最终被垃圾收集器拾取。
我想创建一个删除节点函数,该函数删除 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
是使用前一个节点的下一个 link 来引用当前节点的下一个 link,因此是当前节点(您希望删除的节点 [中间的节点])将丢失引用并最终被垃圾收集器拾取。