~~~~~~~ 队列是一个有序的列表,具有“先进先出”的特点,可以通过数组或者链表来实现,本文主要通过Java代码介绍数组实现。
~~~~~~~
因为队列具有“先进先出”的特点,所以数据的输出及输入分别从队列的首和尾来进行,通常使用front
记录首,rear
记录尾,maxSize
来表示该队列的最大容量。
~~~~~~~ 在实现环形队列时,思路如下:
front
指向队列的第一个元素,初值为0;rear
指向队列最后一个元素的后一个位置(空出一个空间作为约定,因此本文所用的方法实现环形队列最大容量为maxSize-1
),初值也为0;- 队列满的条件为:
(rear+1)%maxSize == front
- 队列为空的条件为:
rear == front
- 队列中有效数据的个数为:
(rear+maxSize-front) % maxSize
~~~~~~~ 本文通过内部类定义队列,同时在main()方法中进行了测试,具体代码如下:
import java.util.Scanner;
public class CircleArrayQueueDemo {
public static void main(String[] args) {
// 下面进行环形队列的测试
// 创建一个队列
CircleArray queue = new CircleArray(3);// 队列有效数据个数最大为2
char key = ' '; // 接收用户输入
Scanner scanner = new Scanner(System.in);
boolean loop = true;
// 输出一个菜单
while (loop){
System.out.println("s: 显示队列");
System.out.println("e: 退出程序");
System.out.println("a: 添加数据到队列");
System.out.println("g: 从队列中取出数据");
System.out.println("h: 查看队列头的数据");
key = scanner.next().charAt(0); // 接收一个字符
switch (key){
case 's':
queue.showQueue();
break;
case 'a':
System.out.println("请输入一个数字");
int value = scanner.nextInt();
queue.addQueue(value);
break;
case 'g':
try {
int res = queue.getQueue();
System.out.printf("取出的数据是%d\n",res);
} catch (Exception e){
System.out.println(e.getMessage());
}
break;
case 'h':
try {
int res = queue.headQueue();
System.out.printf("队列头的数据是%d\n",res);
} catch (Exception e){
System.out.println(e.getMessage());
}
break;
case 'e':
scanner.close();
loop = false;
break;
}
}
System.out.println("程序退出");
}
}
class CircleArray {
private int maxSize; // 数组的最大容量
private int front; // 队列头(指向第一个元素)
private int rear; // 队列尾(指向最后一个元素的后一个位置)
private int[] arr; // 该数组用于存放数据,模拟队列
// 构造方法
public CircleArray(int arrMaxSize) {
maxSize = arrMaxSize;
arr = new int[maxSize];
front = 0;
rear = 0;
}
// 判断队列是否满
public boolean isFull() {
return (rear + 1) % maxSize == front;
}
// 判断队列是否为空
public boolean isEmpty() {
return front == rear;
}
// 添加数据到队列
public void addQueue(int n) {
// 判断队列是否满
if (isFull()) {
System.out.println("队列已满,不能加入数据");
return;
}
arr[rear] = n;
rear = (rear + 1) % maxSize; // rear后移,必须考虑取模!
}
// 数据出队列
public int getQueue() {
// 判断队列是否空
if (isEmpty()) {
// 通过抛出异常处理
throw new RuntimeException("队列为空,不能取数据");
}
int value = arr[front]; // 先把front对应的值保存到一个临时变量
front = (front + 1) % maxSize; // front后移(取模)
return value;
}
// 显示队列所有数据(遍历)
public void showQueue() {
if (isEmpty()) {
System.out.println("队列为空,没有数据");
return;
}
// 遍历思路:从front开始
for (int i = front; i < front + size(); i++) {
System.out.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];
}
}