代码实现:
package com.afmobi;
import java.util.Scanner;
public class CircleArrayQueueDemo {
public static void main(String[] args) {
CircleArray queue = new CircleArray(5); // 其队列的有效数据最大为4,最后一个位置为预留位置
Scanner scanner = new Scanner(System.in);
boolean loop = true;
while(loop) {
System.err.println("s(show): 显示队列");
System.err.println("a(add): 添加数据到队列");
System.err.println("g(get): 从队列取出数据");
System.err.println("h(head): 查看队列头元素");
System.err.println("e(exit): 程序");
char key = scanner.next().charAt(0); //接受一个字符
switch (key) {
case 's':
queue.showQueue();
break;
case 'a':
System.out.println("输入一个数");
int nextInt = scanner.nextInt();
queue.addQueue(nextInt);
break;
case 'g':
try {
int data = queue.getQueue();
System.out.printf("取出的数据是%d\n",data);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}
break;
case 'h':
try {
int headQueue = queue.headQueue();
System.out.printf("队列头元素是%d\n",headQueue);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}
break;
case 'e':
scanner.close();
loop = false;
break;
default:
break;
}
}
System.out.println("程序已退出");
}
}
class CircleArray{
private int maxSize; //数组最大容量
private int front; // 指向队列第一个元素
private int rear; // 指向队列的最后一个元素的的后一个位置,希望预留一个位置作为约定!不放入元素!
private int[] arr; // 队列
public CircleArray(int arrMaxSize) {
super();
maxSize = arrMaxSize;
arr = new int[maxSize];
// front = 0;
// rear = 0;
// front和rear初始值都为0,
}
// 判断队列是否满
public boolean isFull() {
return (rear + 1) % maxSize == front;
/** 关键点:比如现在有个 maxSize为5的队列,预约了最后一个空位置,
* 所以队列满的时候应该是下角标3的元素,此时rear下角标为4也就是预约的位置,
* ( 4 + 1 ) % 5 = 0 = front (头元素); 环形队列最重要的就是 % 运算来更新front和rear的角标位置来复用队列
*/
}
// 判断队列是否为空
public boolean isEmpty() {
return rear == front; // 起始位置就是队列为空
}
// 添加数据到队列
public void addQueue(int n) {
if (isFull()) {
System.out.println("队列已满,不能添加数据了!!!");
return;
}
//直接加数据
arr[rear] = n;
// 将rear 后移;考虑取模
rear = (rear + 1) % maxSize ;
}
// 获取队列的数据,出队列
public int getQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空,不能取数据");
}
//直接取数据
int value = arr[front];
// 将front 取模后移,考虑取模
front = (front + 1) % maxSize ;
return value;
}
// 显示队列的所有数据
public void showQueue() {
if (isEmpty()) {
System.err.println("队列空的,没有数据");
return;
}
// 从front开始,遍历多少个有效元素
for (int i = front; i < front + size() ; i++) {
System.err.printf("arr[%d]=%d\n", i % maxSize,arr[i % maxSize]); //下角标考虑环形所以要取模
}
}
// 求出当前队列有效数据的个数
public int size() {
return (rear + maxSize - front) % maxSize;
}
// 显示头元素
public int headQueue() {
if (isEmpty()) {
throw new RuntimeException("队列为空,没有数据");
}
return arr[front];
}
}
运行过程这里不再叙述,请大家自己测试。