题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:首先明确队列是“先进先出”,栈是“先进后出”,使用两个栈模拟队列,那么可以使用一个栈A接收输入(即push),在pop操作中,将栈A的元素一一弹出,存入另一个栈B中,那么这时栈B的栈顶元素就是模拟队列的出队元素。
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() {
while(!stack1.isEmpty())
{
stack2.push(stack1.pop());
}
// 栈2 的栈顶元素就是队列的出队元素
int out=stack2.pop();
// 把栈2所有元素存入栈1,恢复原来次序
while(!stack2.isEmpty())
{
stack1.push(stack2.pop());
}
return out;
}
}