package com.lon.queue;
import java.util.Scanner;
public class CircleArrayQueueDemo {
public static void main(String[] args) {
CircleArray arrayQueue=new CircleArray(4);//有效数据最大为3,因为rear的位置,以及isFull()算法,预留了一个空的位置
char key;
Scanner scanner=new Scanner(System.in);
boolean loop=true;
System.out.println("数组模拟环形队列:\n");
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):显示头部数据\n");
key = scanner.next().charAt(0);//next()对象的字符
switch (key) {
case 's':
arrayQueue.showQueue();
break;
case 'e':
scanner.close();
loop = false;
break;
case 'a':
System.out.println("输入加入的值\n");
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
arrayQueue.addQueue(a);
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 res1 = arrayQueue.headQueue();
System.out.printf("头部的数据为:%d\n", res1);
} catch (Exception e) {
System.out.println(e.getMessage());
}
default:
break;
}
}
}
}
class CircleArray{
private int maxSize;//数组最大容量
private int front;//队列头, front指向队列的第一个元素,初始值为0
private int rear;//队列尾,rear指向最后一个元素,初始值为0
private int[]arr;//存储数据,模拟队列
//构造器
public CircleArray(int max){
maxSize=max;//front rear默认为0
arr=new int[max];
}
//判断是否满
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;
} else {
arr[rear] = n;
rear=(rear+1)% maxSize; //rear后移,循环以防止越界
}
}
//出队列
public int getQueue(){
int value;
if(isEmpty())//抛出异常
throw new RuntimeException("队列空,无法取数据");
else{
value=arr[front];
front=(front+1) % maxSize;
return value;
}
}
//求有效数据的个数
public int size(){
return (rear-front+maxSize)%maxSize;
}
//显示队列所有数据
public void showQueue(){
if(isEmpty()){
System.out.println("队列为空");
return;
}
else
for(int i=front;i<front+size();i++)
System.out.printf("arr[%d]=%d \n",i%maxSize,arr[i%maxSize]);
}
//显示队列头数据,不取
public int headQueue(){
if(isEmpty())
{
throw new RuntimeException("队列为空");
}
else
return arr[front];
}
}