gpt4 book ai didi

python - 在 Python 中从链表中删除头节点

转载 作者:太空宇宙 更新时间:2023-11-04 04:05:27 24 4
gpt4 key购买 nike

我一直在研究 Python 中的链表。我能够创建节点、链接节点和添加新节点,但我真的坚持删除节点,尤其是当节点中存在的元素与根指针所在的 header (列表中的第一个节点)匹配时指向它。

我已经编写了一个条件来检查输入元素是否与头节点中的元素匹配,如果找到,我已将根指针更改为下一个节点指针,但仍然无法删除该节点。

下面是我创建的删除节点的函数:

import copy
class Node:
def __init__(self,data=None):
self.data=data
self.pointer=None

class Llist:
def __init__(self):
self.rootpointer=None

def addlist(self,newdata):
self.newdata=newdata
node4=Node(newdata)
node4.pointer=self.rootpointer
self.rootpointer=node4

def Dispaylist(self):
self.cpyrootpointer=copy.deepcopy(self.rootpointer)
while self.cpyrootpointer is not None :
print (self.cpyrootpointer.data)
self.cpyrootpointer=self.cpyrootpointer.pointer

def removeitem(self,item):
self.item=item
self.cpyrootpointerr=copy.deepcopy(self.rootpointer)
curr=self.cpyrootpointerr
while self.cpyrootpointerr is not None:
if(self.cpyrootpointerr.data==item):
self.cpyrootpointerr=curr.pointer
break




linkedlist=Llist()
linkedlist.rootpointer=Node('A')
linkedlist.rootpointer.pointer=Node('B')
linkedlist.rootpointer.pointer.pointer=Node('C')

linkedlist.addlist('D')
linkedlist.Dispaylist()

linkedlist.addlist('E')
print('break')
linkedlist.Dispaylist()
linkedlist.removeitem('E')
linkedlist.Dispaylist()

我在列表中有 E-->D--->A-->B-->C。在调用 removeitem() 函数后,我想要的是 D--->A-->B-->C,但我又得到了 E-->D--->A-->B-->C .

最佳答案

您不是在更改根指针,而是在更改副本。 “self.cpyrootpointerr=curr.pointer”应该是“self.rootpointer = curr.pointer”。请注意,这仅处理列表中第一项被删除的情况。

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com