package Array;
import org.junit.Test;
import java.util.Scanner;
//数组模拟环形队列实现 实现重复利用数组 达到循环利用的效果
public class CircleQueue {
@Test
public void test() {
CircleArrayQueue circleQueue = new CircleArrayQueue(4); //预留了一个空间,有效空间是maxSize-1
char t = ' '; //接受用户输入
Scanner sc = new Scanner(System.in);
boolean flag = true;
while (flag) {
System.out.println("s(show) 查看队列所有信息");
System.out.println("a(add) 往队列添加数据");
System.out.println("g(get) 往队列取出数据");
System.out.println("h(head) 查看队列头数据");
System.out.println("e(exit) 退出! ! !");
System.out.println("请输入字符:");
t = sc.next().charAt(0);
switch (t) {
case 's':
circleQueue.showQueue();
break;
case 'a':
try {
System.out.println("请输入一个数字:");
int num = sc.nextInt();
circleQueue.addQueue(num);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'g':
try {
System.out.println("取出的数据是:" + circleQueue.getQueue());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h':
try {
System.out.println("队列头数据是:" + circleQueue.headQueue());
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'e':
sc.close();
flag = false;
break;
default:
break;
}
}
System.out.println("成功退出程序~~~~");
}
}
class CircleArrayQueue {
//定义数组最大值
private int maxSize;
private int[] arr;
private int front; //头指针 指向队列第一个元素
private int rear; //尾指针 指向队列最后一个元素的后面 预留一个空间
//构造方法初始化队列
public CircleArrayQueue(int maxSize) {
this.maxSize = maxSize;
if (maxSize < 1) {
throw new RuntimeException("初始化队列不能小于1");
}
front =0;
rear =0;
arr = new int[maxSize];
}
//数组内有效个数 (rear-front+maxSize)%maxSize
public int size(){
return (rear-front+maxSize)%maxSize;
}
//判断队列是否为空 如果front ==rear 队列为空
public boolean isEmpty() {
return front == rear;
}
/* 0->1>2 ->0 ->1 */
//判断队列是否满了 rear ==maxSize-1 队列满了
public boolean isFull() {
return (rear+1)%maxSize== front;
}
//addQueue 添加队列方法
public void addQueue(int num) {
//先判断队列是否满了
if (isFull()) {
throw new RuntimeException("队列满了~~请稍等");
}
//再往队列里添加数据
arr[rear] = num; //已经指向第一个元素
//要循环使用
rear=(rear+1)%maxSize;
}
//showQueue 显示队列所有数据
public void showQueue() {
if (isEmpty()) {
System.out.println("队列为空~~~");
}
//要从front 开始 遍历front+有效个数
for (int i =front; i < front+size(); i++) {
System.out.printf("a[%d]=%d\t", i%maxSize, arr[i%maxSize]); //这里i=front 也会循环变化
}
System.out.println();
}
//getQueue 取出队列中的数据
public int getQueue() {
//判断队列是否为空
if (isEmpty()) {
throw new RuntimeException("队列为空~~~");
}
//先保存当前front的值
int value=front;
front=(front+1)%maxSize;
return arr[value];
}
//headQueue 查看队列头的数据
public int headQueue() {
//判断队列是否为空
if (isEmpty()) {
throw new RuntimeException("队列为空~~~");
}
return arr[front%maxSize];
}
}