Removing a node in a linked list in python

To remove a node in a linked list, what is wrong with this implementation ?:

def delete(self, val): tmp = self.head prev = None while tmp: if val == tmp.data: self.size -= 1 if prev==None: self.head = self.head.next else: prev.next = tmp.next else: prev = tmp tmp = tmp.next 

All the conductors that I looked at say that it should be:

 def delete(self, data): tmp = self.head prev = None found = False while tmp and not found: if data == tmp.data: found = True else: prev = tmp tmp = tmp.next if found: self.size -= 1 if prev == None: self.head = self.head.next else: prev.next = tmp.next 

but I can’t understand why I need to find it . Why is this necessary? Why is this implementation more correct?

Also, I have the same search issue:

My implementation:

 def __contains__(self, data): tmp = self.head while tmp: if data == tmp.data: return True else: tmp = tmp.next return False 

but the correct implementation is:

 def __contains__(self, data): tmp = self.head found = False while tmp and not found: if data == tmp.data: found = True else: tmp = tmp.next return found 
+4
source share
1 answer

delete identical as long as the data is unique. So in general, it’s better to do separate transitions on the list, from working on elements. It is more readable and less nested. It would be even better to give an error if data not found:

 def delete(self, data): tmp = self.head prev = None while tmp: if data == tmp.data: break prev = tmp tmp = tmp.next else: raise ValueError('data not found') self.size -= 1 if prev is None: self.head = tmp.next else: prev.next = tmp.next 
+2
source

All Articles