public class CircleQueue {
private int maxSize; //有一个数据是空的,用于rear的约定,实际数据容量比maxsize少一个
private int front = 0; //指向队列头部的第一个元素
private int rear = 0; //指向队列尾部最后一个数据的后一位置,默认情况没有数据最后一位是-1
private int[] array;
public CircleQueue(int maxSize) {
this.maxSize = maxSize;
this.array = = new int[maxSize];
}
private boolean isFull() {
return (rear + 1) % maxSize == front; //加1后判断指正尾部和头部数值是否一致
}
private boolean isEmpty() {
return front == rear;
}
public void addQueue(int value) {
if (isFull()) {
System.out.println("队列满的");
return;
}
array[rear] = value;
rear = (rear + 1) % maxSize;
}
public int getQueue() {
if (isEmpty()) {
throw new RuntimeException("队列空的");
}
int value = array[front];
front = (front + 1) % maxSize;
return value;
}
public int headQueue() {
if (isEmpty()) {
throw new RuntimeException("队列空的");
}
return array[front];
}
public void show() {
if (isEmpty()) {
System.out.println("队列空的");
return;
}
for (int i = front; i < front + getDataSize(); i++) {
System.out.printf("array[%d]=%d\n", i % maxSize, array[i % maxSize]);
}
}
private int getDataSize() {
return (rear + maxSize - front) % maxSize; //队列数据最多一列,相当于求绝对值
}
}