使用两个栈来回倒腾可以实现队列。
AC代码:
import java.util.Stack;
public class Queue {
private Stack<Integer> stack1;
private Stack<Integer> stack2;
public Queue() {
stack1=new Stack<>();
stack2=new Stack<>();
}
public void push(int element) {
stack1.push(element);
}
public int pop() {
dump(stack1,stack2);
int res=stack2.pop();
dump(stack2,stack1);
return res;
}
public int top() {
dump(stack1,stack2);
int res=stack2.peek();
dump(stack2,stack1);
return res;
}
private void dump(Stack<Integer> stack1,Stack<Integer> stack2){
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
}
题目来源: http://www.lintcode.com/zh-cn/problem/implement-queue-by-two-stacks/