剑指offer(二)之用两个栈实现队列

思路:先定义两个栈,栈1和栈2,需要入栈时,把值都入栈到栈1,出栈时,把栈1的值出栈到栈2,然后栈2再依次出栈。

import java.util.Stack;

public class stackinandout{

Stack<Integer> stack1=new Stack<Integer>();

Stack<Integer> stack2=new Stack<Integer>();

public void push(int value){

stack1.push(new Integer(value));

}

public int pop(){

if(stack2.isEmpty()){

while(stack1.isEmpty()){

stack2.push(stack1.pop);

}

}

return stack2.pop().intValue();

}

}


你可能感兴趣的:(栈,push,pop,用两个栈实现队列)