環形隊列實現類:
public class CycleQueue {
private int maxSize; // 表示數組的最大容量
//front 變量的含義做一個調整: front 就指向隊列的第一個元素, 也就是說 arr[front] 就是隊列的第一個元素 front 的初始值 = 0
private int front;
//rear 變量的含義做一個調整:rear 指向隊列的最後一個元素的後一個位置. 因爲希望空出一個空間做爲約定.rear 的初始值 = 0
private int rear;
private int[] arr; // 該數組用於存放數據, 模擬隊列
//構造函數,用來初始化
public CycleQueue(int maxSize) {
this.maxSize = maxSize;
arr = new int[maxSize];
}
// 判斷隊列是否滿
public boolean isFull() {
return (rear + 1) % maxSize == front;
}
// 判斷隊列是否爲空
public boolean isEmpty() {
return rear == front;
}
// 添加數據到隊列
public void addCycleQueue(int n) {
// 判斷隊列是否滿
if (isFull()) {
System.out.println("隊列滿,無法添加數據");
return;
}
//直接將數據加入
arr[rear] = n;
//將 rear 後移
rear = (rear + 1) % maxSize;
}
// 獲取隊列的數據, 出隊列
public int getCycleQueue() {
// 判斷隊列是否空
if (isEmpty()) {
throw new RuntimeException("隊列空,不能取數據");
}
// front是指向隊列的第一個元素
// 1. 先把 front 對應的值保留到一個臨時變量
// 2. 將 front 後移, 考慮取模
// 3. 將臨時保存的變量返回
int value = arr[front];
front = (front + 1) % maxSize;
return value;
}
// 顯示隊列的所有數據
public void showAllCycleQueue() {
if (isEmpty()) {
System.out.println("隊列空的,無法顯示數據");
return;
}
for (int i = front; i < front + size() ; i++) {
System.out.printf("arr[%d]=%d\n", i % maxSize, arr[i % maxSize]);
}
}
// 求出當前隊列有效數據的個數
public int size() {
// rear = 2
// front = 1
// maxSize = 3
return (rear + maxSize - front) % maxSize;
}
// 顯示隊列的頭數據, 注意不是取出數據
public int showFrontCycleQueue() {
// 判斷
if (isEmpty()) {
throw new RuntimeException("隊列空的,無法出隊");
}
return arr[front];
}
}
測試程序,測試環形隊列的各種操作:
public class CycleQueueDemo {
public static void main(String[] args) {
CycleQueue cycleQueue = new CycleQueue(5);
System.out.println("---------向隊列中添加元素-------------------");
cycleQueue.addCycleQueue(1);
cycleQueue.addCycleQueue(2);
cycleQueue.addCycleQueue(3);
cycleQueue.addCycleQueue(4);
System.out.println("--------------顯示隊列中的所有元素----------------------");
cycleQueue.showAllCycleQueue();
System.out.println("--------------判斷隊空----------------------");
System.out.println(cycleQueue.isEmpty());
System.out.println("--------------判斷隊滿----------------------");
System.out.println(cycleQueue.isFull());
System.out.println("--------------顯示隊頭元素----------------------");
System.out.println(cycleQueue.showFrontCycleQueue());
System.out.println("--------------隊首元素出隊----------------------");
System.out.println(cycleQueue.getCycleQueue());
}
}