双向链表也叫双链表,是链表的一种,它的每个数据结点中都有两个指针,分别指向直接后继和直接前驱。所以,从双向链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点。一般我们都构造双向循环链表。
1 class Node(): 2 '''节点类''' 3 def __init__(self, elem): 4 '''节点的两个参数,本身值elem以及指向下一个节点的地址next''' 5 self.elem = elem 6 self.next = None 7 self.prev = None 8 9 10 class DoubleLinkList(): 11 '''双链表''' 12 def __init__(self, node = None): 13 self.__head = None 14 15 def sing_append(self, elem): 16 '''链表尾部添加元素''' 17 node = Node(elem) 18 if self.is_empty(): 19 self.__head = node 20 else: 21 cur = self.__head 22 while cur.next != None: 23 cur = cur.next 24 cur.next = node 25 node.prev = cur 26 27 def is_empty(self): 28 '''判断链表是否为空,第一次传入数据以后self.__head将永远指向node1对象''' 29 return self.__head is None 30 31 def sing_length(self): 32 '''链表长度''' 33 cur = self.__head 34 # 将第一个元素的node实例赋值给cur, 35 count = 0 36 while cur != None: 37 count+=1 38 cur = cur.next 39 return count 40 41 def sing_travel(self): 42 '''遍历整个列表''' 43 cur = self.__head 44 # 即将node1对象赋值给cur 45 while cur != None: 46 print(cur.elem) 47 cur = cur.next 48 49 def sing_add(self, item): 50 node = Node(item) 51 node.next = self.__head 52 self.__head = node 53 node.next.prev = node 54 55 def sint_insert(self, pos, item): 56 if pos <= 0: 57 self.sing_add(item) 58 elif pos > self.sing_length()-1: 59 self.sing_append(item) 60 else: 61 cur = self.__head 62 count = 0 63 while count < pos: 64 count += 1 65 cur = cur.next 66 node = Node(item) 67 node.next = cur 68 node.prev = cur.prev 69 cur.prev.next = node 70 cur.prev = node 71 72 def sing_search(self,item): 73 cur = self.__head 74 while cur != None: 75 cur = cur.next 76 if item == cur.elem: 77 return True 78 return False 79 80 def sing_remove(self, item): 81 cur = self.__head 82 while cur != None: 83 if item == cur.elem: 84 if cur == self.__head: 85 self.__head = cur.next 86 if cur.next: 87 # 判断链表是否只有一个节点 88 cur.next.prev = self.__head 89 break 90 else: 91 cur.prev.next = cur.next 92 if cur.next: 93 cur.next.prev = cur.prev 94 break 95 else: 96 cur = cur.next 97 98 if __name__ == "__main__": 99 ll = DoubleLinkList() 100 ll.sing_append(1) 101 ll.sing_append(2) 102 # ll.sing_add(8) 103 ll.sing_append(3) 104 ll.sint_insert(-1,5) 105 ll.sing_travel() 106 print(ll.sing_search(5)) 107 ll.sing_remove(3) 108 ll.sing_travel()