# python數據結構中實現隊列的幾種方法

### 1.list實現 enqueue append() dequeue pop(0) 或 enqueue insert(0,item) dequeue pop()

``````MAX_SIZE = 100
class MyQueue1(object):
"""模擬隊列"""

def __init__(self):
self.items = []
self.size = 0

def is_empty(self):
"""判斷是否爲空"""
return self.size == 0

def size(self):
"""返回隊列的大小"""
return self.size

def enqueue(self, item):
"""入隊(加入元素)"""
self.items.append(item)
self.size += 1

def dequeue(self):
"""出隊(彈出元素)"""
if self.size < MAX_SIZE and self.size >= 0:
self.size -= 1
return self.items.pop(0)
else:
print("隊列已經爲空")
return None

def getFront(self):
if not self.is_empty():
return self.items[0]
else:
return None

def getRear(self):
if not self.is_empty():
return self.items[self.size-1]
else:
return None

def __str__(self):
return str(self.items)

class MyQueue2(object):
"""模擬隊列"""
def __init__(self):
self.items = []
self.size = 0

def is_empty(self):
"""判斷是否爲空"""
return self.size == 0

def size(self):
"""返回隊列的大小"""
if self.size <= MAX_SIZE:
return self.size

def enqueue(self, item):
"""入隊(加入元素)"""
if self.size <= MAX_SIZE:
self.items.insert(0, item)
self.size += 1

def dequeue(self):
"""出隊(彈出元素)"""
if self.size > 0 and self.size <= MAX_SIZE:
self.size -= 1
return self.items.pop()
else:
print("隊列已經爲空")
return None

def getFront(self):
"""返回隊頭元素"""
if not self.is_empty():
return self.items[0]
else:
return None
def getRear(self):
if not self.is_empty():
return self.items[self.size-1]
else:
return None

def __str__(self):
return str(self.items)

def test(obj):
i = obj()
for x in range(0,6):
i.enqueue(x)
print(i)
i.dequeue()
print(i, i.getFront(), i.getRear(), i.size)

if __name__ == "__main__":
test(MyQueue1)
test(MyQueue2)
``````

### 2.鏈隊 前文已介紹

``````class Node():
def __init__(self, value=None):
self.value = value
self.next = None

class StcakQueue():
def __init__(self):
self.front = Node()
self.rear = Node()
self.size = 0

def enqueue(self, value):
node = Node(value)
if self.size == 0:
self.front = node
self.rear = node
else:
self.rear.next = node
self.rear = node
self.size += 1

def dequeue(self):
if self.size == 0:
raise Exception('queue is empty')
else:
temp = self.front.value
self.front = self.front.next
self.size -= 1
return temp

def is_empty(self):
if self.size == 0 :
return False
else:
return True

def top(self):
if self.size == 0 :
raise LookupError('queue is empty')
else:
return self.front.value

def size(self):
return self.size

def __str__(self):
if self.size == 0:
return None
else:
stack_list = []
temp, count = self.front, self.size
while count > 0 :
stack_list.append(temp.value)
temp = temp.next
count -= 1
return str(stack_list)

if __name__ == "__main__":
i = StcakQueue()
for x in range(0,6):
i.enqueue(x)
print(i)
i.dequeue()
print(i, i.size)
``````

``````class Node(): #結點類
def __init__(self,elem):
self.elem = elem # 數據域，用來存放數據元素
self.next = None # 指針域，指向下一個結點

def __str__(self):
return str(self.elem)

class Queue(): # 隊列
def __init__(self): # 隊列初始化

def is_empty(self):

def enqueue(self,elem): # 進隊列（正常向後填元素）
node = Node(elem) # 創建新結點
else:
while current.next is not None:
current = current.next
current.next = node

def dequeue(self): # 出隊列（頭出）
if not self.is_empty():
return current.elem
else:
raise IndexError('pop from a empty stack')

def size(self):
count = 0
while current.next is not None:
current = current.next
count += 1
return count

def __repr__(self):
stack_list = []
while current.next is not None:
stack_list.append(current.next.elem)
current = current.next
return str(stack_list)

__str__ = __repr__

if __name__ == "__main__":
i = Queue()
for x in range(0, 6):
i.enqueue(x)
print(i)

i.dequeue()
print(i, i.size())
``````

### 3.兩個棧實現一個隊列 O(1)

``````class CQueue:
def __init__(self):
self.stack1 = []
self.stack2 = []

def append_tail(self, elem):
self.stack1.append(elem)

if not self.stack2:
if self.stack1:
while self.stack1:
elem = self.stack1.pop()
self.stack2.append(elem)
else:
raise Exception("Queue is empty.")

elem = self.stack2.pop()
return elem

#學習中遇到問題沒人解答？小編創建了一個Python學習交流羣：711312441
def unitest():
# Create an instance of class CQueue
que = CQueue()
print("Push 1, 2, 3 successively into CQueue.")
for i in range(1, 4):
que.append_tail(i)
print("Push 4, 5, 6 successively into CQueue.")
for i in range(4, 7):
que.append_tail(i)
# Pop the rest elements in the queue
for i in range(4):