题解 | #用两个栈实现队列#
用两个栈实现队列
http://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
队列:1 2 -(队列)-> 1 2 栈 : 1 2 -(栈一)->2 1-(栈二)->1 2 入栈时直接插入栈一。 出栈时先检查栈二是否为空,为空则把栈一放入栈二,然后从栈二出栈。
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() {
if (stack2.size()==0)
while (!stack1.empty()) {
stack2.push(stack1.pop());
}
return stack2.pop();
}
}