题解 | #用两个栈实现队列#
用两个栈实现队列
http://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
//每次入栈时,先检查出栈是否为空
if(stack2.empty() && !stack1.empty()){
//将入栈的以前的元素弹出到出栈
stack2.add(stack1.pop());
}
//再入栈
stack1.add(node);
}
public int pop() {
//如果出栈不为空,直接出栈
if(!stack2.empty()){
return stack2.pop();
}
//将入栈的元素全部弹出到出栈中
while(!stack1.empty()){
stack2.add(stack1.pop());
}
return stack2.pop();
}
}