两个队列实现栈

 1 class StackWithTwoQueues:
 2     def __init__(self):
 3         self.queue1 = []
 4         self.queue2 = []
 5 
 6     def push(self, item):
 7         if len(self.queue1) == 0:
 8             self.queue1.append(item)
 9             while self.queue2:
10                 self.queue1.append(self.queue2.pop(0))
11         elif len(self.queue2) == 0:
12             self.queue2.append(item)
13             while self.queue1:
14                 self.queue2.append(self.queue1.pop(0))
15 
16     def pop(self):
17         if self.queue1:
18             return self.queue1.pop(0)
19         elif self.queue2:
20             return self.queue2.pop(0)
21         else:
22             return None
23 
24 
25 stack = StackWithTwoQueues()
26 stack.push(1)
27 stack.push(2)
28 stack.push(3)
29 stack.push(4)
30 stack.push(5)
31 print(stack.pop())
32 print(stack.pop())
33 print(stack.pop())
34 print(stack.pop())
35 stack.push(2)
36 stack.push(3)
37 stack.push(4)
38 stack.push(5)
39 print('=================')
40 print(stack.pop())
41 print(stack.pop())
42 print(stack.pop())
43 print(stack.pop())
44 print(stack.pop())

  

posted @ 2018-12-17 19:28  zhaoweibin  阅读(96)  评论(0编辑  收藏  举报