用栈实现队列

实现思想:对于A,B两个栈,A作为压栈,B作为弹出栈。
push操作时,将结果压入A栈,并且判断B栈是否为空,如果为空,则将A栈的元素全部移动到B栈
pop操作时,判断A,B栈是否为空,如果同时为空,则跑抛出异常,如果不同时为空,判断B栈是否有元素。
如果没有元素,则将A栈中元素全部移动到B栈中,进行弹出。

public class StackToQueue {
    private Stack<Integer> stackpush;
private Stack<Integer> stackpop;
public StackToQueue(){
stackpop = new Stack<>();
stackpush = new Stack<>();
}
public void push(int number){
stackpush.push(number);
dao();
}
public Integer pop(){
if(stackpush.isEmpty()&&stackpop.isEmpty()){
throw new RuntimeException("the Queue is null");
}
dao();
return stackpop.pop();
}
public Integer peek(){
if(stackpush.isEmpty()&&stackpop.isEmpty()){
throw new RuntimeException("the Queue is null");
}
dao();
return stackpop.peek();
}
//设置一个判断,如果B栈为空,则将A栈数据移动到B栈
public void dao(){
if(!stackpop.isEmpty())
return;
while (!stackpush.isEmpty()){
stackpop.push(stackpush.pop());
}
}
}
总结:使用两个栈进行配合,注意判断栈是否为空。

猜你喜欢

转载自www.cnblogs.com/liuwentao/p/9383819.html