Data-Structures-using-Python
Data-Structures-using-Python copied to clipboard
Delete function in LinkedList.py not working
@OmkarPathak, In the delete method in linkedlist.py the last element will be deleted if the given key is not present and if only the head node is present then there will a reference error for prev node.
So I have made some changes and it works
# deleting an item based on data(or key)
def delete(self, data):
temp = self.head
# if data/key is found in head node itself
if(temp.data == data):
self.head = temp.next
temp = None
return
else:
# else search all the nodes
while(temp.next):
if(temp.data == data):
break
prev = temp #save current node as previous so that we can go on to next node
temp = temp.next
# node not found
if temp == None:
return
prev.next = temp.next
return
@bharathikannann Yep, there is an error in @OmkarPathak's code. Yours works fine, but check mine out, I feel your code has some steps that can be skipped. It's in my DSA-stuff repo.
def removeAtData(self, data):
if self.head and self.head.data == data:
self.head = self.head.next
return
temp = self.head
prev = None
while temp and temp.data != data:
prev = temp
temp = temp.next
if temp is None:
print('The element is not in the list.')
return
prev.next = temp.next