剑指offer

Q1: 使用两者栈实现一个队列,完成队列的push和pop操作,队列中的元素是int类型

思路:

压入元素直接压入statck1,删除元素先查看statck2是否为空,非空就弹出;空则将stack1中元素取出,置于stack2中。

1
2
3
4
5
6
7
8
9
10
11
12
public class  {
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.empty()){
while(!stack1.empty())
stack2.push(stack1.pop());
}
return stack2.pop();