环形队列实现类:
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());
}
}