需要注意的是
队列容量为maxSize - 1
判断队列为空 rear == front
判断是否为满 (rear + 1) % maxSize == front
或者 (rear - front + maxSize) % maxSize == maxSize - 1
获取元素个数:(rear + maxSize - front) % maxSize
class AnnularArrayQueue {
private int maxSize;
private int front;//队列头
private int rear;//队列尾
private int[] arr;//模拟队列
// 初始化
public AnnularArrayQueue(int arrMaxSize) {
maxSize = arrMaxSize;
front = 0;//指向队列头部前一个位置
rear = 0;//指向队列尾部(即包含最后一个数据)
arr = new int[arrMaxSize];
}
//判断队列满
public boolean isFull() {
System.out.println((rear + 1) % maxSize == front);
// return (rear + 1) % maxSize == front;
return (rear - front + maxSize) % maxSize == maxSize - 1;
}
// 判断队列是否为空
public boolean isEmpty() {
return rear == front;
}
// 队列添加数据
public void addQueue(int n) {
if (isFull())
return;
arr[rear] = n;
rear = (rear + 1) % maxSize;
}
// 出队列
public int pullQueue() {
if (isEmpty())
throw new RuntimeException("Queue Empty!");
int data = arr[front];
front = (front + 1) % maxSize;
return data;
}
// 显示队列数据
public void showQueue() {
if (isEmpty())
System.out.println("空");
for (int i = front; i < front + getSize(); i++) {
System.out.print("array[" + i + "]=" + arr[i%maxSize] + "\n");
}
}
// 显示头数据
public int headQueue() {
if (isEmpty())
throw new RuntimeException("Queue Empty!");
return arr[front];
}
// 获取元素个数
public int getSize(){
return (rear - front +maxSize) % maxSize;
}
}