用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
这是一道比较经典的题,解法有多种,同样的还有用两个队列实现栈,leetcode上的原题。
此解法是push的时候把stack1弹向stack2,然后再从stack2弹回来。
mport java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
while(!stack1.isEmpty())
{
stack2.push(stack1.pop());
}
stack2.push(node);
while(!stack2.isEmpty())
{
stack1.push(stack2.pop());
}
}
public int pop() {
return stack1.pop();
}
}