关键步骤-取模值
- front初值为0,指向队列第一个元素
- rear初值为0,指向队列最后一个元素的后一个位置
这里多出来的一个空间是为了区分队列满和队列空 - 判断队列为空:rear = front
- 判断队列满:(rear + 1)%maxSize = front
- 队列容量 = (rear - front + maxSize)%maxSize
代码实现
class CircleArray {
private int maxSize;
private int front;
private int rear;
private int[] arr;
public CircleArray(int arrMaxSize) {
this.maxSize = arrMaxSize;
arr = new int[maxSize];
front = 0;
rear = 0;
}
public boolean isFull() {
return (rear + 1) % maxSize == front;
}
public boolean isEmpty() {
return rear == front;
}
public void addQueue(int n) {
if (isFull()) {
System.out.println("队列满,不能加数据");
return;
}
arr[rear] = n;
rear = (rear + 1) % maxSize;
}
public int getQueue() {
if (isEmpty()) {
System.out.println("队列空,不能取数据");
}
int value = arr[front];
front = (front + 1) % maxSize;
return value;
}
public void showQueue() {
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]);
}
}
public int size() {
return (rear + maxSize - front) % maxSize;
}
public int headQueue() {
if (isEmpty()) {
throw new RuntimeException("队列空,不能取数据");
}
return arr[front];
}
}
import java.util.Scanner;
public class CircleArrayQueueDemo {
public static void main(String[] args) {
System.out.println("------测试数组完成环形队列代码------");
CircleArray arrayQueue = new CircleArray(4);
char key = ' ';
Scanner scanner = new Scanner(System.in);
boolean loop = true;
while (loop) {
System.out.println("s(show):显示队列");
System.out.println("e(exit):退出程序");
System.out.println("a(add):添加数据到队列");
System.out.println("g(get):从队列中取出数据");
System.out.println("h(head):查看队列头的数据");
System.out.println();
key = scanner.next().charAt(0);
switch (key) {
case 's':// 展示队列的所有数据
arrayQueue.showQueue();
break;
case 'e':
scanner.close();
loop = false;
break;
case 'a':// 添加数据到队列
System.out.println("请输入要添加的数");
int value = scanner.nextInt();
arrayQueue.addQueue(value);
break;
case 'g':// 取数据
try {
int res = arrayQueue.getQueue();
System.out.printf("取出的数据是%d\n", res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h':
try {
int res = arrayQueue.headQueue();
System.out.printf("队列的头数据是%d\n", res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
default:
break;
}
}
}
}