陣列實作佇列
//陣列實作佇列
class queue{
int[] a = new int[5];
int i = 0;
//入隊操作
public void in(int m) {
a[i++] = m;
}
// 出佇列操作 取出最前面的值 通過回圈遍歷把所有的資料向前一位
public int out() {
int index = 0;
int temp = a[0];
for(int j = 0;j < i;j++) {
a[j] = a[j + 1];
}
return temp;
}
}
ArrayList實作佇列
//集合實作佇列
class queue{
List<Integer> list = new ArrayList<Integer>();
int index = 0;
public void in(int n) {
list.add(n);
index++;
}
//出佇列操作
//出隊
public int out(){
if(!list.isEmpty()){
index--;
return list.remove(0);
}
return -1;
}
}
兩個堆疊實作佇列
//兩個堆疊實作一個佇列
class queue3 {
Stack<Integer> stackA = new Stack<Integer>();
Stack<Integer> stackB = new Stack<Integer>();
//入隊
public void in(int n) {
stackA.push(n);
}
//出隊 我們把A里面的元素遍歷拿出放入B中 再拿出B中的第一個元素
public int out() {
//判斷b堆疊有沒有元素 有回傳false 無回傳真
if(stackB.isEmpty()) {
while(!stackA.isEmpty()) {
stackB.push(stackA.pop());
}
}
return stackB.pop();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/46645.html
標籤:AI
下一篇:以下怎么解決呀?
