在現(xiàn)實中可霎,我們?nèi)ャy行辦理業(yè)務(wù)的時候就需要排隊。你來的早宴杀,排在前面癣朗,就會越早的離開。而在你排的隊就是一個隊列旺罢。
隊列是個有序列表旷余,它遵循先進先出的原則。
根據(jù)隊列的先進先出的原則扁达,我們就可以用代碼來實現(xiàn)一個隊列正卧。
- 首先在一個ArrayQueue類中創(chuàng)建一個數(shù)組來代表一個隊列
private int[] arrayQueue; // 創(chuàng)建一個數(shù)組
private int maxSize; // 隊列的最大長度
private int front; // 隊頭
private int rear; // 隊尾
- 然后我們要將這些信息進行初始化
public ArrayQueue(int max) {
this.maxSize = max; // 獲取隊列的長度用來初始化隊列
this.arrayQueue = new int[maxSize];
this.front = -1; //一開始都是沒有數(shù)據(jù),所以頭和尾都為-1
this.rear = -1;
}
- 然后是對隊列的一些操作
// 判斷隊列是否已滿
// 當隊尾到達最大值時跪解,隊列已滿( 數(shù)組能儲存的最大下標為 n - 1 )
public boolean isFull() {
return rear == maxSize - 1;
}
// 判斷隊列是否為空
// 當隊頭和隊尾在同一位置時炉旷,則說明隊列中間沒有內(nèi)容,即為空叉讥。
public boolean isEmpty() {
return front == rear;
}
// 添加數(shù)據(jù)
// 添加數(shù)據(jù)時要先判斷隊列是否已滿
public void addQueue(int n) {
if(isFull()){
System.out.println("隊列已滿窘行,不能加入數(shù)據(jù)");
return;
}
rear ++;
arrayQueue[rear] = n;
}
// 從隊列中拿出數(shù)據(jù)
// 同理要先判斷隊列里是否有數(shù)據(jù)
// 根據(jù)先進先出原則來取數(shù)據(jù)
public int getQueue() {
if(isEmpty()) {
throw new RuntimeException("隊列為空,不能取出數(shù)據(jù)");
}
front ++;
return arrayQueue[front];
}
// 遍歷隊列
// 當隊列為空時图仓,直接顯示隊列為空隊列
public void showQueue() {
if (isEmpty()) {
System.out.println("隊列為空罐盔,沒有數(shù)據(jù)");
return;
}
for (int i = 0; i < arrayQueue.length; i++)
System.out.print(arrayQueue[i] + " ");
System.out.println();
}
在這個隊列中存在一個問題:只能使用一次,不能達到復用的效果救崔。
而這個問題的解決辦法為:循環(huán)隊列惶看。
循環(huán)隊列