[英]Deleting a Head Node from Linked List in Python
I have been working on linked lists in Python.我一直在研究 Python 中的链表。 I was able to create nodes, link nodes, and add new nodes, but I am really stuck at deleting the node, especially the case when the element present in the node matches with the header (first node in list) where the root pointer is pointing to it.
我能够创建节点、链接节点和添加新节点,但我真的坚持删除节点,尤其是当节点中存在的元素与根指针所在的头(列表中的第一个节点)匹配时指向它。
I have written a condition to check that the input element matches with the element in the header node and, if found, I have changed the root pointer to the next node pointer but am still not able to delete the node.我编写了一个条件来检查输入元素是否与头节点中的元素匹配,如果找到,我已将根指针更改为下一个节点指针,但仍然无法删除该节点。
Below is the function I have created to delete the node:下面是我创建的删除节点的函数:
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()
I have E-->D--->A-->B-->C in the list.我在列表中有 E-->D--->A-->B-->C。 What I want is D--->A-->B-->C after I call the removeitem() function, but I am getting E-->D--->A-->B-->C again.
我想要的是 D--->A-->B-->C 在我调用 removeitem() 函数后,但我再次得到 E-->D--->A-->B-->C .
You are not changing the root pointer, you are changing a copy.您不是在更改根指针,而是在更改副本。 "self.cpyrootpointerr=curr.pointer" should be "self.rootpointer = curr.pointer".
“self.cpyrootpointerr=curr.pointer”应该是“self.rootpointer = curr.pointer”。 Be aware that this only handles the case where the first item on the list is being deleted.
请注意,这仅处理列表中第一项被删除的情况。
See delete function in this post请参阅此帖子中的删除功能
class LinkedList(Node):
...
def delete(self,value):
temp = self.__head
while temp!=None:
if temp.value == value and temp == self.__head:
self.__head = temp.ref
del temp
self.__count -= 1
break
elif temp.ref != None and temp.ref.value == value:
temp_ref = temp.ref.ref
del temp.ref
self.__count -= 1
temp.ref = temp_ref
break
temp = temp.ref
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.