public class ArrayQueue {
// 表示数组最大容量
private int maxSize;
// 队列首元素之前的元素的下标
private int front;
// 队列尾元素下标
private int rear;
// 用来存放数据(模拟队列)
private int[] arr;
// 队列构造器
public ArrayQueue(int maxSize) {
this.maxSize = maxSize;
arr = new int[maxSize];
// 队列首有效元素的前一个位置的索引
front = -1;
// 队列尾有效元素的索引
rear = -1;
}
// 判断队列是否满
public boolean isFull() {
return rear == maxSize-1;
}
// 判断队列是否空
public boolean isEmpty() {
return rear == front;
}
// 入列
public void addQueue(int val) {
// 判断是否满
if(isFull()) {
System.out.println("队列满");
return;
}
arr[++rear] = val;
}
// 出列
public int getQueue() {
// 判断是否空
if(isEmpty())
throw new RuntimeException("队列空");
return arr[++front];
}
// 打印队列数据
public void showQueue() {
if(isEmpty()) {
System.out.println("队列空");
return;
}
for(int i = 0; i < maxSize; i++)
System.out.printf("arr[%d] = %d\n", i, arr[i]);
}
// 显示首有效元素(不是取)
public int headQueue() {
if(isEmpty())
throw new RuntimeException("队列空");
return arr[front + 1];
}
}
将数组看成环形
public class CircleArrayQueue {
// 表示数组最大容量
private int maxSize;
// 队列首元素下标
private int front;
// 队列尾元素的后一个位置的下标
private int rear;
// 用来存放数据(模拟队列)
private int[] arr;
// 队列构造器
public CircleArrayQueue(int maxSize) {
this.maxSize = maxSize + 1;
// 因为需要保留其中一个位置作为 [标识位], 故创建的数组大小要大一个元素空间
arr = new int[maxSize + 1];
// 初始化
front = 0;
rear = 0;
}
// 判断队列是否满
public boolean isFull() {
return (rear + 1) % maxSize == front;
}
// 判断队列是否空
public boolean isEmpty() {
return rear == front;
}
// 入列
public void addQueue(int val) {
// 判断是否满
if(isFull()) {
System.out.println("队列满");
return;
}
arr[rear] = val;
// rear后移时要考虑到:rear指向的是数组末尾位置
rear = (rear + 1) % maxSize;
}
// 出列
public int getQueue() {
// 判断是否空
if(isEmpty())
throw new RuntimeException("队列空");
int val = arr[front];
// front后移时要考虑到:front指向的是数组末尾位置
front = (front + 1) % maxSize;
return val;
}
// 当前队列有效元素个数
public int getCount() {
return (rear - front + maxSize) % maxSize;
}
// 打印队列数据
public void showQueue() {
if(isEmpty()) {
System.out.println("队列空");
return;
}
// 思路:从front开始遍历,遍历count个元素
int count = getCount();
for(int i = front; i < front + count; i++)
System.out.printf("arr[%d] = %d\n", i%maxSize, arr[i%maxSize]);
}
// 显示首有效元素(不是取)
public int headQueue() {
if(isEmpty())
throw new RuntimeException("队列空");
return arr[front];
}
}
原文:https://www.cnblogs.com/liujiaqi1101/p/12214382.html