【问题标题】:Removing a node in a Linked List using Links使用链接删除链接列表中的节点
【发布时间】:2015-03-03 16:23:49
【问题描述】:

我想创建一个删除节点函数,该函数删除在 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

【问题讨论】:

  • 您打算如何让您的方法知道要删除哪个节点?你说“从头部开始删除给定位置的节点”。但是您的方法不接受计数参数,并且不引用列表的头部,也不进行任何计数。需要考虑的一些事项。
  • 也许有点这样。 “从我的脑海中数数”部分在哪里?另请注意,您要查找的是要删除的节点preceding,并将node.link = node.link.link 应用于该节点。
  • 对不起,我使用了旧代码,这是我刚刚编辑问题的新代码

标签: python linked-list


【解决方案1】:

删除节点的最简单方法是创建对currentNodepreviousNode 的引用,如下所示。

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 的next 链接来引用currentNode 的next 链接,因此currentNode(您希望删除的节点[中间节点])将失去引用并最终被垃圾收集器拾取.

【讨论】:

  • 非常感谢您对我的帮助!
  • 不客气!确保您真正了解 LinkedList。这是一个非常重要的数据结构,可以很容易地调整为其他数据结构,如堆栈或队列。现在去练习吧! :)
猜你喜欢
  • 2015-11-14
  • 2015-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-05
相关资源
最近更新 更多