1. 程式人生 > >python 實現雙端隊列

python 實現雙端隊列

eve iter 循環雙端隊列 else ise __init__ app col remove

# 隊列兩端都可以進行push和pop操作。 push操作可以用循環雙端隊列的append,appendleft。
# pop操作使用循環雙端隊列的romove

class Node(object): # 結點有兩個指針
    def __init__(self, maxsize = None, value = None, next = None, prev = None):
        self.maxsize = maxsize
        self.value = value
        self.next = next
        self.prev 
= prev class Dqueue(object): def __init__(self, maxsize = None): self.maxsize = maxsize node = Node() node.next = node node.prev = node # 最開始的只有根結點,它自己兩個指針指向自己 self.root = node self.length = 0 def __len__(self): return self.length
def headnode(self): return self.root.next def tailnode(self): return self.root.prev def push(self, value): # 在右端壓入值,相當於循環雙端鏈表的append if self.maxsize is not None and len(self) >= self.maxsize: raise Exception(full) node = Node(value = value) tailnode
= self.tailnode() # 獲取尾結點, 這個這次append 是插入的第一個結點。 尾結點就是self.root (根結點) tailnode.next = node node.prev = tailnode node.next = self.root self.root.prev = node self.length += 1 def pushleft(self, value): if self.maxsize is not None and len(self) >= self.maxsize: raise Exception(full) node = Node(value = value) if self.root.next == self.root: # 最初只有一個根結點的情況 self.root.next = node self.root.prev = node node.next = self.root node.prev = self.root else: head = self.root.next node.next = head node.prev = self.root self.root.next = node head.prev = node self.length += 1 def remove(self, node): # 註意這裏傳入的是一個node, 不是傳入一個值。 為了,降低算法復雜度 if node is self.root: return "不能移除根結點" node.prev.next = node.next node.next.prev = node.prev self.length -= 1 del node def iter_node(self): # 遍歷結點 if self.root.next == self.root: # 只有根結點 return "隊列為空" curnode = self.root.next while curnode.next is not self.root: yield curnode curnode = curnode.next yield curnode # 尾結點也要遍歷 def __iter__(self): for node in self.iter_node(): yield node.value def iter_node_reverse(self): # 反向遍歷 if self.root.prev is self.root: return curnode = self.root.prev # tailnode while curnode.prev is not self.root: yield curnode curnode = curnode.prev yield curnode def pop(self): tailnode = self.tailnode() self.remove(tailnode) def popleft(self): head = self.headnode() self.remove(head) def test_Dqueue(): # 測試函數 就測試了主要的pop和push dq = Dqueue() dq.push(1) dq.push(2) assert len(dq) == 2 assert list(dq) == [1,2] dq.pushleft(3) assert list(dq) == [3,1,2] dq.pop() assert list(dq) == [3,1] dq.popleft() assert list(dq) == [1]

python 實現雙端隊列