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
source share