思路分析
- 创建一个指定容量
maxSize
的数组,用于存放队列元素;
- 声明
front
和rear
,front指向队列头的前一个位置,rear指向队列的当前尾部位置;
- 当添加数据时
rear
向后rear = (rear + 1) % maxSize
,如果(rear + 1) % maxSize == front
则说明队列满了;
- 取出数据时
front
向后front = (front + 1) % maxSize
,如果front == rear
则说明队列空了;
代码实现
public class ArrayQueue {
// 最大容量
private final int maxSize;
// 队列前端,指向队列头部的前一个位置
private int front;
// 队列尾端,指向队列尾部的当前位置
private int rear;
// 用于存储元素
private int[] arr;
public ArrayQueue(int maxSize) {
this.maxSize = maxSize;
rear = -1;
front = -1;
arr = new int[maxSize];
}
// 队列是否已满
private boolean isFull() {
return (rear + 1) % maxSize == front;
}
// 队列是否已空
private boolean isEmpty() {
return front == rear;
}
public void add(int v) throws Exception {
if(isFull()) {
throw new Exception("队列已满");
}
this.rear = (this.rear + 1) % maxSize;
arr[this.rear] = v;
}
public int get() throws Exception {
if(isEmpty()) {
throw new Exception("队列已空");
}
this.front = (this.front + 1) % maxSize;
return arr[this.front];
}
}