class Node: def __init__(self, data): self.data = data self.next = None def __repr__(self): return self.data def __len__(self): l = 0 while self != None: l += 1 self = self.next return l def __iter__(self): curr = self while self != None: yield self self = self.next def print(self): for curr in self: print(curr) def addToTail(self, data): """ Add a single item to tail of list """ while self.next != None: self = self.next self.next = Node(data) def addListToTail(self, values): """ Add multiple items to tail of list """ while self.next != None: self = self.next for v in values: self.next = Node(v) self = self.next def deleteNode(self, data): prev = None curr = self while curr != None: if curr.data == data: break prev = curr curr = curr.next # Item not found, nothing to delete, return head if curr == None: return self # delete from head, just return new head. # Note: python GC will auto delete head node if prev == None: return self.next # delete middle or tail prev.next = curr.next del curr # return new head return selffellowship = Node("Gandalf")fellowship.addToTail("Frodo")fellowship.addToTail("Sam")fellowship.addListToTail(["Merry", "Pippin"])fellowship.addListToTail(["Aragorn", "Gimli", "Legolas"])fellowship.addListToTail(["Boromir"])print("### From Rivendel:", len(fellowship))fellowship.print()fellowship = fellowship.deleteNode("Boromir")print("### After Amon Hen", len(fellowship))fellowship.print()fellowship = fellowship.deleteNode("Gandalf")print("### After Khazad-dรปm", len(fellowship))fellowship.print()