。。。剑指Offer之——用两个栈实现队列。。。

 1 //    stack1用来表示入栈
 2     Stack<Integer> stack1 = new Stack<Integer>();
 3 //    stack2用来表示出栈
 4     Stack<Integer> stack2 = new Stack<Integer>();
 5 
 6 //    队列的入队,就用stack1进行入栈
 7     public void push(int node) {
 8         stack1.push(node);
 9     }
10 
11     public int pop() {
12 //        队列出队的时候,如果stack2为空,就把stack1里面所有的元素加入到stack2中
13         if(stack2.isEmpty()){
14             while (!stack1.isEmpty()){
15                 stack2.push(stack1.pop());
16             }
17         }
18 //        队列出队的时候,如果stack2不为空,直接返回stack2的栈顶元素
19         return stack2.pop();
20     }

猜你喜欢

转载自www.cnblogs.com/yingmeng/p/10769308.html
今日推荐