我想创建一个删除节点函数,删除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
答案 0 :(得分:1)
删除节点的最简单方法是创建对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(您要删除的节点[中间的节点])将丢失引用并最终被垃圾收集器。