1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
| class HeroNode: def __init__(self, no, name, nickname): self.no = no self.name = name self.nickname = nickname self.next = None
def __str__(self): return f"HeroNode{{no={self.no}, name='{self.name}', nickname='{self.nickname}'}}"
class SingleLinkedList: def __init__(self): self.head = HeroNode(0, "", "")
def add(self, hero_node): temp = self.head while temp.next is not None: temp = temp.next temp.next = hero_node
def add_by_order(self, hero_node): temp = self.head flag = False while temp.next is not None: if temp.next.no > hero_node.no: break elif temp.next.no == hero_node.no: flag = True break temp = temp.next if flag: print("准备插入的编号已经存在,不能加入") else: hero_node.next = temp.next temp.next = hero_node
def update(self, hero_node): if self.head.next is None: print("链表为空") return temp = self.head.next flag = False while temp.next is not None: if temp.no == hero_node.no: flag = True break temp = temp.next if flag: temp.nickname = hero_node.nickname temp.name = hero_node.name else: print("未找到编号")
def delete(self, hero_node): if self.head.next is None: print("链表为空") return temp = self.head flag = False while temp.next is not None: if temp.next.no == hero_node.no: flag = True break temp = temp.next if flag: temp.next = temp.next.next else: print("要删除的不存在")
def display(self): if self.head.next is None: print("链表为空") return temp = self.head.next while temp is not None: print(temp, end=" -> ") temp = temp.next print("None")
if __name__ == "__main__": hero_node1 = HeroNode(1, "一号", "1号") hero_node2 = HeroNode(2, "二号", "2号") hero_node3 = HeroNode(3, "三号", "3号") hero_node4 = HeroNode(4, "四号", "4号") hero_node5 = HeroNode(4, "四号", "4号") hero_node6 = HeroNode(6, "六号", "6号")
single_linked_list = SingleLinkedList() single_linked_list.add(hero_node1) single_linked_list.add(hero_node2) single_linked_list.add(hero_node3) single_linked_list.add(hero_node4)
single_linked_list.display() single_linked_list.delete(hero_node3) single_linked_list.display()
|