剑指Offer_编程题_用两个栈来实现队列

链接:https://www.nowcoder.com/questionTerminal/54275ddae22f475981afa2244dd448c6?f=discussion
来源:牛客网

题目描述

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

解题思路

队列是先进先出,栈是先进后出,如何用两个栈来实现这种先进先出呢?

其实很简单,我们假设用stack1专门来装元素,那么直接stack1.pop肯定是不行的,这个时候stack2就要发挥作用了。

我们的规则是:只要stack2中有元素就pop,如果stack2为空,则将stack1中所有元素倒进satck2中,就是说,新元素只进stack1,元素出来只从stack2出来。

这样子,就能保证每次从stack2pop出来的元素就是最老的元素了。

 

 

我的答案


链接:https://www.nowcoder.com/questionTerminal/54275ddae22f475981afa2244dd448c6?f=discussion
来源:牛客网

import java.util.Stack;
 
public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
     
    public void push(int node) {
        stack1.push(node);
    }
     
    public int pop() {
        if(stack1.empty()&&stack2.empty()){
            throw new RuntimeException("Queue is empty!");
        }
        if(stack2.empty()){
            while(!stack1.empty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}

 



测试代码

public class StackTest {

public static void main(String[] args) {
Solution solution = new Solution();
new Thread(() -> {
while (true) {
System.out.println(solution.pop());
}
}).start();
for (int i = 0; i < 10; i++) {
solution.push(i);
}
}


}

 

posted @ 2020-04-07 21:15  _Phoenix  阅读(200)  评论(0编辑  收藏  举报