python - 从链表中删除节点

标签 python linked-list

我想创建一个 delete_node 函数,从第一个节点开始删除列表中该位置的节点作为计数。到目前为止,这是我的代码:

class node:
    def __init__(self):
        self.data = None # contains the data
        self.next = None # contains the reference to the next node

class linked_list:
    def __init__(self):
        self.cur_node = None

    def add_node(self, data):
        new_node = node() # create a new node
        new_node.data = data
        new_node.next = self.cur_node # link the new node to the 'previous' node.
        self.cur_node = new_node #  set the current node to the new one.

    def list_print(self):
        node = ll.cur_node
        while node:
            print node.data
            node = node.next
    def delete_node(self,location):
        node = ll.cur_node
        count = 0
        while count != location:
            node = node.next
            count+=1
        delete node


ll = linked_list()
ll.add_node(1)
ll.add_node(2)
ll.add_node(3)

ll.list_print()

最佳答案

您不应该在 Python 中从字面上删除一个节点。如果没有任何东西指向该节点(或者更准确地说,在 Python 中,没有任何东西引用它),无论如何它最终都会被虚拟机销毁。

如果 n 是一个节点并且它有一个 .next 字段,那么:

n.next = n.next.next 

有效丢弃n.next,使n.next字段指向n.next.next 相反。如果 n 是要删除的节点之前的节点,则相当于在 Python 中将其删除。

[附言最后一段可能有点困惑,直到你在纸上勾勒出来 - 然后它应该变得非常清楚]

关于python - 从链表中删除节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4654953/

相关文章:

python - 为什么 YARN 集群模式下的 spark-submit 在执行器上找不到 python 包?

c - 为什么节点没有正确添加以及为什么它打印相反? (单链表)

Python if/elif 问题与 random.randint

python - 在字符串中搜索符合特定条件的子串

python - 从 MySQL 语句获取结果并存储在 Python 列表中并检查条件

C 双向链表插入

c - C++ 函数和方法中的链表

c++ - 打印通过 Copy Constructor 创建的 e2 会使程序崩溃

c++ - 在不调用析构函数的情况下追加到队列

python - 如何更新存储在 Django 缓存中的字典?