1、源码
CircleArrayQueue
package com.study.queue;//使用数组模拟一个队列public class CircleArrayQueue {private int maxSize;//表示数组的最大容量private int front;//队列头,初始值为0private int rear;//队列尾,初始值为0private int[] arr;//该数组用于存放数据,模拟队列//创建队列构造器public CircleArrayQueue(int arrMaxSize) {maxSize = arrMaxSize;arr = new int[maxSize];}//判断队列是否满public boolean isFull() {return (rear+1)%maxSize==front;}//判断队列是否空public boolean isEmpty() {return front == rear;}//添加数据到队列public void addQueue(int n) {if (isFull()) {System.out.println("队列满,不能加数据");return;}arr[rear] = n;rear = (rear+1)%maxSize;}//获取队列的数据public int getQueue() {if (isEmpty()) {throw new RuntimeException("队列空,不能去数据");}int value= arr[front];front = (front+1)%maxSize;return value;}//显示队列所有数据public void show() {if (isEmpty()) {System.out.println("队列空,没有数据");return;}for (int i = front; i < front + size(); i++) {System.out.println(arr[i%maxSize]);}}//求出当前数组有效数据的个数public int size(){return (rear+maxSize-front)%maxSize;}//显示队列的头数据public int headQueue() {if (isEmpty()) {throw new RuntimeException("队列空,没有数据");}return arr[front];}}
CircleArrayQueueDemo
package com.study.queue;import java.util.Scanner;public class CircleArrayQueueDemo {public static void main(String[] args) {CircleArrayQueue queue = new CircleArrayQueue(4);String key = null;Scanner scanner = new Scanner(System.in);boolean loop = true;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),显示队列头的数据");while (loop) {key = scanner.nextLine();switch (key) {case "s":queue.show();break;case "a":System.out.println("输入一个数");int value = scanner.nextInt();queue.addQueue(value);break;case "g":try {int res = queue.getQueue();System.out.println("取出的数据是" + res);} catch (Exception e) {System.out.println(e.getMessage());}break;case "h":try {int res = queue.headQueue();System.out.println("队列头的数据是" + res);} catch (Exception e) {System.out.println(e.getMessage());}break;case "e":scanner.close();loop = false;break;default:break;}}System.out.println("程序退出");}}
2、运行结果


通过环形队列,可以解决数组只能使用一次的问题
3、总结
尾索引的下一个为头索引时表示队列满,即将队列容量空出一个作为约定,这个在做判断队列满的时候需要注意 (rear + 1) % maxSize == front [满]
rear == front [空]
