两个栈实现队列
1.判断队列为空: 当栈s1 和 s2都为空时,那么队列为空
2.入队操作: 直接将数据加入到s1栈中
3.出队操作:当 s2 栈不为空的时候, s2 栈直接执行出栈操作就可以得到出队的数据;
如果 s2 栈为空的话,则 s2 入栈 s1 出栈的数据,直到 s2 栈为空。
4.查看队列首数据:和出队操作一样
1 #!/usr/bin/env python3 2 # -*- coding: utf-8 -*- 3 4 5 class Queue(object): 6 def __init__(self): 7 self.s1 = Stack() 8 self.s2 = Stack() 9 10 def is_empty(self): 11 result = self.s1.is_empty() and self.s2.is_empty() 12 return result 13 14 def enqueue(self, elem): 15 self.s1.push(elem) 16 17 def dequeue(self): 18 while self.s2.is_empty(): 19 while not self.s1.is_empty(): 20 self.s2.push(self.s1.pop()) 21 return self.s2.pop() 22 23 def peek(self): 24 while self.s2.is_empty(): 25 while not self.s1.is_empty(): 26 self.s2.push(self.s1.pop()) 27 return self.s2.peek() 28 29 class Stack(object): 30 def __init__(self): 31 self._elems = [] 32 33 def is_empty(self): 34 return self._elems == [] 35 36 def push(self, elem): 37 self._elems.append(elem) 38 39 def pop(self): 40 return self._elems.pop() 41 42 def peek(self): 43 return self._elems[-1] 44 45 def bianli(self): 46 return self._elems 47 48 if __name__ == "__main__": 49 s = Stack() 50 for i in range(5): 51 s.push(i) 52 print(s.pop()) 53 print(s.pop()) 54 print(s.bianli()) 55 q = Queue() 56 for i in range(5): 57 q.enqueue(i) 58 print("enqueue 0 1 2 3 4 ") 59 print("dequeue:",q.dequeue()) 60 print("dequeu:",q.dequeue())