[英]Deleting a Head Node from Linked List in Python
我一直在研究 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。 我想要的是 D--->A-->B-->C 在我調用 removeitem() 函數后,但我再次得到 E-->D--->A-->B-->C .
您不是在更改根指針,而是在更改副本。 “self.cpyrootpointerr=curr.pointer”應該是“self.rootpointer = curr.pointer”。 請注意,這僅處理列表中第一項被刪除的情況。
請參閱此帖子中的刪除功能
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.