题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
解题思路
队列的特性是先进先出,栈的特性是先进后出。
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(!stack2.empty()){
//有,则直接弹出
return stack2.pop();
}else{
//没有,则把主栈全部弹出,插入辅助栈
while (!stack1.empty()){
stack2.push(stack1.pop());
}
//弹出辅助栈栈顶
return stack2.pop();
}
}
}