链接:https://www.nowcoder.com/questionTerminal/54275ddae22f475981afa2244dd448c6?f=discussion
来源:牛客网
题目描述
用两个栈来实现一个队列,完成队列的Push
和Pop
操作。 队列中的元素为int类型。
解题思路
队列是先进先出,栈是先进后出,如何用两个栈来实现这种先进先出呢?
其实很简单,我们假设用stack1
专门来装元素,那么直接stack1.pop
肯定是不行的,这个时候stack2
就要发挥作用了。
我们的规则是:只要stack2
中有元素就pop
,如果stack2
为空,则将stack1
中所有元素倒进satck2
中,就是说,新元素只进stack1
,元素出来只从stack2
出来。
这样子,就能保证每次从stack2
中pop
出来的元素就是最老的元素了。
我的答案
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.isEmpty() && stack2.isEmpty()) {
throw new RuntimeException("queue empty");
}
while (!stack1.isEmpty()) {
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);
}
}
}