题解 | #用两个栈实现队列#
用两个栈实现队列
http://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6
这道题比较简单。
stack1负责存入push的值。
stack2负责弹出pop的值,如果stack2为空的时候就将stack1倒入到stack2中,再弹出stack2的值。
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.isEmpty()) {
return stack2.pop();
}
while(!stack1.isEmpty()) {
int value = stack1.pop();
stack2.push(value);
}
return stack2.pop();
}
} 
查看9道真题和解析