题解 | #用两个栈实现队列#
用两个栈实现队列
http://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
两个栈里面,stack1用于获取元素并存入栈中;stack2在pop()方法中和stack1共同使用:首先将stack1里面的所有元素依次弹出并压入stack2,这样stack2栈顶的元素即是“最先进入队列的元素”,弹出stack2的栈顶元素之后,stack2的元素依次弹出,存回stack1。
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node); //压入stack1
}
public int pop() {
//元素出stack1进stack2实现先入先出
while (stack1.size()!=0) {
stack2.push(stack1.pop());
}
int top = stack2.pop(); //弹出元素赋给top
//剩余元素存回stack1
while (stack2.size()!=0) {
stack1.push(stack2.pop());
}
return top;
}
}