1 class Node(object): 2 3 def __init__(self, value=None): 4 self.value = value 5 self.next, self.prev = None, None 6 7 class Circular_Double_Linked_List(object): 8 9 def __init__(self, maxsize=None): 10 self.root = Node()
#我习惯于从空的链表开始就是个循环链表 11 self.root.next = self.root 12 self.root.prev = self.root 13 self.count = 0 14 self.maxsize = maxsize 15 16 def __len__(self): 17 return self.count 18 19 def append(self, value):
#这里的意思是如果maxsize不为None的前提下 len(self) >= self.maxsize 20 if self.maxsize is not None and len(self) >= self.maxsize: 21 raise Exception("Linked List Full") 22 node = Node(value) 23 tailnode = self.root.prev 24 tailnode.next = node 25 node.next = self.root 26 self.root.prev = node 27 node.prev = tailnode 28 self.count += 1 29 30 def append_left(self, value): 31 if self.maxsize is not None and len(self) >= self.maxsize: 32 raise Exception("Linked List Full") 33 headnode = self.root.next 34 node = Node(value) 35 self.root.next = node 36 node.next = headnode 37 headnode.prev = node 38 node.prev = self.root 39 self.count += 1 40 41 def iter_node(self): 42 curnode = self.root.next 43 while curnode is not self.root: 44 yield curnode 45 curnode = curnode.next 46 47 def __iter__(self): 48 for node in self.iter_node(): 49 yield node.value 50 51 def find(self, value): 52 for index,node in enumerate(self.iter_node()): 53 if node.value == value: 54 return index 55 return -1 56 57 def remove(self, node): 58 if node is self.root: 59 raise Exception('remove empty Liked List') 60 prevnode = node.prev 61 nextnode = node.next 62 prevnode.next = nextnode 63 nextnode.prev = prevnode 64 value = node.value 65 del node 66 self.count -= 1 67 return value
#这里也可以实现 O(1)操作的pop和popleft
def popleft(self): if self.root.next is self.root: raise Exception('pop from a empty linked list') headnode = self.root.next self.root.next = headnode.next headnode.next.prev = self.root value = headnode.value del headnode self.count -= 1 return value
def pop(self): if self.root.next is self.root: raise Exception('pop from a empty linked list') tailnode = self.root.prev self.root.prev = tailnode.prev tailnode.prev.next = self.root value = tailnode.value del tailnode self.count -= 1 return value
68 69 if __name__ == "__main__": 70 cl = Circular_Double_Linked_List() 71 assert list(cl) == [] 72 for i in range(5): 73 cl.append(i) 74 assert len(cl) == 5 75 assert list(cl) == [0, 1, 2, 3, 4] 76 assert cl.find(3) == 3 77 assert cl.find(5) == -1