用两个栈实现队列

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

 1 # -*- coding:utf-8 -*-
 2 class Solution:
 3     def __init__(self):
 4         self.list1 = []
 5         self.list2 = []
 6         
 7     def push(self, node):
 8         self.list1.append(node)
 9         # write code here
10     def pop(self):
11         if len(self.list2) == 0:
12             while len(self.list1) > 1:
13                 top = self.list1.pop(-1)
14                 self.list2.append(top)
15             return self.list1.pop(-1)
16         return self.list2.pop(-1)
17         # return xx

 

leetcode地址,Java版代码:

 1 class CQueue {
 2     Stack<Integer> S1;
 3     Stack<Integer> S2;
 4     public CQueue() {
 5         S1 = new Stack<Integer>();
 6         S2 = new Stack<Integer>();
 7     }
 8     public void appendTail(int value) {
 9         S1.push(value);
10     }        
11     public int deleteHead() {
12         if(S2.isEmpty()) {
13             while(!S1.isEmpty()) {
14                 int top = S1.pop();
15                 S2.push(top);
16             }
17         }
18         if(!S2.isEmpty()){
19             int cur = S2.pop();
20             return cur;
21         }
22         return -1;
23     }
24 }

 

posted on 2019-06-12 22:03  Sempron2800+  阅读(102)  评论(0编辑  收藏  举报