Reputation: 15
The below code snippet is for deleting a node in linked list. My class contains two members namely data
and next
a pointer to hold other objects of that class type. When, I run my program, I don't get any error. If I try to delete the first item in the linked list, it enters the First for loop and displays the message "The data is found". But if I print my list, I am seeing the element in the list. I think this is because of assigning objects back, but I am not able to find where I have done that mistake. Any help is greatly appreciated.
def deleteNode(self, a_data):
flag = 0
if (self.data == a_data):
print("The data is found")
self = self.next
flag = 1
else:
while(self.next != None):
if (self.next.data == a_data):
self.next = self.next.next
flag = 1
break
else:
self = self.next
if(flag):
print("Data Deleted")
else:
print("Data not available")
Thanks
Upvotes: 1
Views: 49
Reputation: 414645
self = self.next
in your code has no effect on the outside world: it just assigns to a local variable.
It looks like you are trying to delete a node from within Node class itself. You could use a function instead that accepts a list head and returns a (possibly new) list head with the corresponding item deleted:
def delete_node(head, data):
"""Delete the first node in the `head` list that has `data`."""
prev, node = None, head
while node is not None: # until the last node (`None` means empty list)
if node.data == data: # found node that has data
if prev is None: # we are at the very beginning of the list
assert head is node
head = node.next # remove the first node
else:
assert prev.next is node
prev.next = node.next # remove internal node
break
prev, node = node, node.next
return head
Upvotes: 1
Reputation: 15
Friends,
I modified my function. I think the error may be because not assigning back the value to the original one, so I made my function to return value. Comments and other methods and any other reason for above than mine are cordially welcome.
def deleteNode(self, a_data):
flag = 0
if (self.data == a_data):
print("The data is found")
self = self.next
flag = 1
else:
while(self.next != None):
if (self.next.data == a_data):
self.next = self.next.next
flag = 1
break
else:
self = self.next
if(flag):
print("Data Deleted")
else:
print("Data not available")
return self
Thanks S
Upvotes: 0