class Node(object): """节点""" def __init__(self, item): self.item = item self.next = None self.prev = None class DoubleLinkList(object): """双链表""" def __init__(self, node=None): self._head = node def is_empty(self): # 和单链表一样 """判断链表是否为空""" return self._head == None def length(self): # 和单链表一样 """链表长度""" # cur游标,用来移动遍历节点 cur = self._head # count记录数量 count = 0 while cur is not None: count += 1 cur = cur.next return count def travel(self): # 和单链表一样 """遍历链表""" # cur游标,用来移动遍历节点 cur = self._head while cur is not None: print(cur.item, end=" ") cur = cur.next print("") def add(self, item): """头部添加元素,头插法""" node = Node(item) if self.is_empty(): self._head = node else: node.next = self._head self._head.prev = node self._head = node def append(self, item): """尾部添加元素,尾插法""" node = Node(item) if self.is_empty(): self._head = node else: # cur游标,用来移动遍历节点 cur = self._head while cur.next is not None: cur = cur.next cur.next = node node.prev = cur def insert(self, pos, item): """指定位置添加元素 :param pos:从0开始 """ if pos <= 0: self.add(item) elif pos > self.length() - 1: self.append(item) else: count = 0 cur = self._head while count < pos: count += 1 cur = cur.next # 退出循环的时候,cur指向pos位置 node = Node(item) node.next = cur node.prev = cur.prev cur.prev.next = node cur.prev = node def remove(self, item): """删除节点""" cur = self._head while cur is not None: if cur.item == item: # 先判断此节点是否是头节点 if cur == self._head: self._head = cur.next if cur.next: # 判断链表是否只有一个节点 cur.next.prev = None else: cur.prev.next = cur.next if cur.next: cur.next.prev = cur.prev break else: cur = cur.next def search(self, item): """链表查找节点是否存在,并返回True或者False""" cur = self._head while cur is not None: if cur.item == item: return True else: cur = cur.next return False if __name__ == "__main__": ll = DoubleLinkList() print(ll.is_empty()) print(ll.length()) ll.add(1) print(ll.is_empty()) print(ll.length()) ll.append(2) ll.append(3) ll.append(4) ll.append(5) ll.append(6) ll.travel() ll.add(8) ll.travel() ll.insert(-1, 66) ll.travel() ll.remove(66) ll.travel() ll.remove(6) ll.travel()