【发布时间】:2019-08-09 20:17:22
【问题描述】:
我一直在研究 Python 中的链表。我能够创建节点、链接节点和添加新节点,但我真的被困在删除节点上,尤其是当节点中存在的元素与根指针所在的标头(列表中的第一个节点)匹配时指向它。
我已经编写了一个条件来检查输入元素是否与头节点中的元素匹配,如果找到,我已将根指针更改为下一个节点指针,但仍然无法删除该节点。
下面是我创建的删除节点的函数:
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.item=item?self.cpyrootpointerr=copy.deepcopy(self.rootpointer)的意义何在??? -
@juanpa.arrivillaga self.item=item 用于需要删除的元素,如果在根标头节点中找到该元素,则应删除该节点并且我有 self.cpyrootpointerr=copy .deepcopy(self.rootpointer) 因为当我第一次调用该函数时,指针一直从最左到右遍历,直到指针指向 None 并且当我们再次调用该函数时,因为它指向 None 它不会显示任何东西,因此我制作了指针的副本并用它来遍历列表
-
为什么要创建实例变量?这些都没有多大意义,你只需要一个
.root属性,而且它永远不需要被深度复制。另外,不是很相关,但 python 没有指针。您复制了该名称引用的整个对象 -
@juanpa.arrivillaga 我对 python 完全陌生,如果它没有多大意义,我真的很抱歉,你能给我一个你想要表达的示例代码,以便我能理解请问?
标签: python python-3.x