双向链表
# 创建节点类 class Node(): def __init__(self,item): # 节点数据 self.item=item # 上一个节点地址 self.pre=None # 下一个节点地址 self.next=None class DoubleLinkList(): def __init__(self,node=None): self.__head=node #判断链表是否为空 def is_empty(self): return self.__head is None # 链表长度 def length(self): cur=self.__head count=0 while cur is not None: cur=cur.next count+=1 return count # 循环链表 def travel(self): cur=self.__head while cur is not None: print(cur.item,end='') cur=cur.next print('') # 搜索节点 def search(self,item): cur=self.__head while cur is not None: if cur.item==item: return True cur=cur.next return False # 头部增加节点 def add(self,item): node=Node(item) node.next=self.__head self.__head=node if node.next: node.next.pre=node # 尾部增加节点 def append(self,item): node=Node(item) if self.is_empty(): self.__head=node else: cur=self.__head while cur.next is not None: cur=cur.next node.pre=cur cur.next=node # 指定位置插入 def insert(self,pos,item): node=Node(item) if pos<=0: self.add(item) elif pos>=self.length(): self.append(item) else: cur=self.__head count=0 while count<pos-1: cur=cur.next count+=1 # 顺序赋值,先和上一个节点链接,再和下一个节点链接,然后下一个节点再和本节点链接 node.pre=cur.pre cur.pre.next=node node.next=cur cur.pre=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: self.__head.pre=None else: cur.pre.next=cur.next if cur.next: cur.next.pre=cur.pre return cur=cur.next if __name__ == '__main__': dd=DoubleLinkList() for i in range(10): dd.append(i) dd.travel() print(dd.length()) dd.travel() dd.add(1) dd.travel() dd.insert(4,5) dd.travel() dd.remove(5) dd.travel() dd.remove(5) dd.travel()