循环队列
实现语言:Java
模板来源:力扣-循环队列
//循环队列,双指针?使用双指针和动态数组,实现循环队列。
创建一个长度为 k 的数组充当循环队列,使用两个变量 front 和 rear 来充当队列头和队列尾(起始均为 0),整个过程 front 始终指向队列头部,rear 始终指向队列尾部的下一位置(待插入元素位置)
class MyCircularQueue {
private int front = 0; // 队首指针
private int rear = 0; // 队尾指针
private List<Integer> arrList;//数组
private int maxSize;//记录长度
public MyCircularQueue(int k) {//初始化队列全部元素为空null
maxSize = k;
arrList = new ArrayList<>(k);
for (int i = 0; i < k; i++) {
arrList.add(null);
}
}
public boolean enQueue(int value) {//添加元素到队列尾部
if (isFull()) {//队列是否已满
return false;
}
arrList.set(rear, value);//记住始终在尾部指针的地方添加元素(第一个元素在0位置添加,以此类推)
rear = (rear + 1) % maxSize;//当尾部指针等于长度时,会变为0(实现循环队列的关键)
return true;
}
public boolean deQueue() {//队列首部元素出栈
if (isEmpty()) {
return false;
}
arrList.set(front, null);//添加使用set方法,方便特殊的位置添加
front = (front + 1) % maxSize;//当首部指针等于长度时,会变为0(实现循环队列的关键)
return true;
}
public int Front() {//得到首部元素
if (isEmpty()) {
return -1;
}
return arrList.get(front);
}
public int Rear() {//得到尾部元素
if (isEmpty()) {
return -1;
}
return arrList.get((rear - 1 + maxSize) % maxSize);
}
public boolean isEmpty() {//判断是否整个队列是否为空
return front == rear && arrList.get(front) == null;//首部指针为空时,且首部指针等于尾部指针,队列全部为空
}
public boolean isFull() {//判断是否已满
return front == rear && arrList.get(front) != null;//尾部指针等于长度-1时,会变为0,且首部指针等于尾部指针,表示队列已满
}
}