队列是一种常见的数据结构,是一种有序列表,可以使用数组或者链表实现,
队列遵循先入先出规则,常见的应用场景有:银行叫号系统,政务大厅排号系统等,使用数组模拟队列示意图如下:
![]()
下面是代码:
public class CircyleArrayQueueDemo {
public static void main(String[] args) {
//测试
CircyleArray arrayQueue = new CircyleArray(4);//有效数据是3,有一个空位
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) 获取头部数据");
key = scanner.next().charAt(0);
switch (key) {
case 's':
arrayQueue.showQueue();
break;
case 'a':
System.out.println("请输入要添加的数据:");
int value = scanner.nextInt();
arrayQueue.addQueue(value);
break;
case 'g':
try {
int res = arrayQueue.getQueue();
System.out.println("取出的数据是 " + res);
} catch (RuntimeException e) {
System.out.println(e.getMessage());
}
break;
case 'h':
try {
int res = arrayQueue.headQueue();
System.out.println("队列头部数据是 " + res);
} catch (RuntimeException e) {
System.out.println(e.getMessage());
}
break;
case 'e':
scanner.close();
loop = false;
break;
default:
break;
}
}
System.out.println("程序退出");
}
}
class CircyleArray {
private int maxSize;//数组队列容量
private int front;//队列头:指向队列第一个元素,arr[front] 初始值 0
private int rear;//指向队列最后一个元素的后一个位置
private int[] arr;//模拟队列的数组
public CircyleArray(int arrMaxSize) {
this.maxSize = arrMaxSize;
arr = new int[maxSize];
}
//判断是否满
public boolean isFull() {
return (rear + 1) % maxSize == front;
}
//判断队列是否空
public boolean isEmpty() {
return rear == front;
}
//添加数据到队列
public void addQueue(int n) {
//判断是否已经满员
if (isFull()) {
System.out.println("队列已满");
} else {
arr[rear] = n;
//后移
rear = (rear + 1) % maxSize;
}
}
//出队列
public int getQueue() {
//判空
if (isEmpty()) {
throw new RuntimeException("空空如也");
} else {
// front 指向 队列第一个元素
//1、先把 front 对应的值保存
int value = arr[front];
//2、front 后移
front = (front + 1) % maxSize;
//3、返回临时变量
return value;
}
}
//遍历队列
public void showQueue() {
if (isEmpty()) {
System.out.println("空空如也");
} else {
//从 front 开始取数
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];
}
}
//有效数据的个数
public int size() {
return (rear + maxSize - front) % maxSize;
}