1. 程式人生 > >用棧實現隊列

用棧實現隊列

isempty row exce 數據 如果 throw 一個 異常 移動

實現思想:對於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());
}
}
}
總結:使用兩個棧進行配合,註意判斷棧是否為空。

用棧實現隊列