package OfferAnswer;
import java.util.Stack;
/**
* 面试题7
* 两个栈实现队列
* @author lwk
*
*/
public class Answer07 {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void add(int value){
//增加方法时,从stack1栈顶加入
stack1.push(value);
}
public int delete() throws Exception{
//删除方法时,从stack2栈顶拿出
if(!stack2.isEmpty()){
return stack2.pop();
}else{//若stack2不为空,则先将stack1中已有元素全部转移到stack2
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
//若此时stack2仍为空,则抛出异常,数组为空
if(stack2.isEmpty()){
throw new Exception("数组为空");
}
return stack2.pop();
}
}
}
剑指offer 面试题7 两个栈实现队列 java版答案
最新推荐文章于 2022-07-12 22:05:48 发布