我想创建一个 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/