class LinkNode(object): def __init__(self, value=None, next=None): self.value = value self.next = next class Link(object): def __init__(self): self.head = None def isempty(self): return self.head == None def add(self, value): # add在头部添加 new_node = LinkNode(value) new_node.next = self.head self.head = new_node def append(self, value): # append(item) 链表尾部添加元素 new_node = LinkNode(value) if not self.head: self.head = new_node else: copy_head = self.head while copy_head.next: copy_head = copy_head.next copy_head.next = new_node def insert(self, index, value): # insert(pos, item) 指定位置添加元素 new_node = LinkNode(value) if 0 < index <= len(self.travel()): count = 0 copy_head = self.head while copy_head: count += 1 if count == index: break copy_head = copy_head.next new_node.next = copy_head.next copy_head.next = new_node elif index == 0: self.add(value) else: self.append(value) def travel(self): copy_head = self.head nodes = [] while copy_head: nodes.append(copy_head.value) copy_head = copy_head.next return nodes def length(self): return len(self.travel()) def search(self, value): return value in self.travel() def remove(self, value): if self.search(value): copy_head = self.head if copy_head.value == value: self.head = self.head.next return True, '删除成功' while copy_head.value != value: if copy_head.next.value == value: copy_head.next = copy_head.next return True, '删除成功' copy_head = copy_head.next return False, '元素不存在' def __repr__(self): nodes = self.travel() return '开头' + '->'.join(nodes) + '结尾' link = Link() link.isempty() link.append('a') link.append('c') link.append('d') link.add('1') link.insert(2, '2') link.remove('a') print(link.travel())
链表
最新推荐文章于 2024-05-02 17:23:00 发布