I have been working on linked lists in 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. What I want is D--->A-->B-->C after I call the removeitem() function, but I am getting E-->D--->A-->B-->C again.