基本概念
队列(Queue)是一个有序的元素集合,其中新元素总是被添加到队尾,而删除操作则发生在队头。 这种特性使得队列成为一种线性数据结构,其操作遵循FIFO(先入先出)原则。
图解
环形队列注意点:
1 有效元素区间为[frount,rear)
2 判断为空:front == rear
3 判断为满:(rear + 1) % 队列长度 == front
基本操作
入队(addQueue):在队尾添加一个新元素。
出队(getQueue):从队头删除一个元素。
队列长度(size):返回队列中当前元素的数量。
判断队列是否为空(isEmpty):检查队列是否为空,如果为空则返回true,否则返回false。
判断队列是否已满(isFull):检查队列是否已满,如果已满则返回true,否则返回false。
展示队列中的内容(showQueue)。
代码演示
class CircleArrayQueue_ {private int maxSize; // 表示数组最大容量private int frount;// frount 变量的含义:frount 就指向队列的第一个元素,也就是arr[frount]private int rear;// rear 队列尾 指向队列最后一个元素的下一个位置,private int[] arr;public CircleArrayQueue_(int arrMaxSize) {maxSize = arrMaxSize;arr = new int[maxSize];}public boolean isFull() {return (rear + 1) % maxSize == frount;}public boolean isEmpty() {return rear == frount;}// 增加数据到队列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[frount];frount = (frount + 1) % maxSize;return value;}// 显示队列数据public void showQueue() {if (isEmpty()) {System.out.println("队列空的,没有数据!");}for (int i = frount; i < size(); frount++) {System.out.println(arr[i]);}}public int size() {return (rear + maxSize - frount) % maxSize;}
}