1. 程式人生 > >python 實現循環雙端鏈表Circular_Double_Linked_List

python 實現循環雙端鏈表Circular_Double_Linked_List

self __main__ class range enume 是個 ike bject 循環鏈表

 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

python 實現循環雙端鏈表Circular_Double_Linked_List