循环队列 - 622. 设计循环队列
设计你的循环队列实现。 循环队列是一种线性数据结构,其操作表现基于
FIFO
(先进先出)原则并且队尾被连接在队首之后以形成一个循环。它也被称为环形缓冲器
。循环队列的一个好处是我们可以利用这个队列之前用过的空间。在一个普通队列里,一旦一个队列满了,我们就不能插入下一个元素,即使在队列前面仍有空间。但是使用循环队列,我们能使用这些空间去存储新的值。
你的实现应该支持如下操作:
MyCircularQueue(k): 构造器,设置队列长度为 k 。 Front: 从队首获取元素。如果队列为空,返回 -1 。 Rear: 获取队尾元素。如果队列为空,返回 -1 。 enQueue(value): 向循环队列插入一个元素。如果成功插入则返回真。 deQueue(): 从循环队列中删除一个元素。如果成功删除则返回真。 isEmpty(): 检查循环队列是否为空。 isFull(): 检查循环队列是否已满。
示例:
MyCircularQueue circularQueue = new MycircularQueue(3); // 设置长度为 3 circularQueue.enQueue(1); // 返回 true circularQueue.enQueue(2); // 返回 true circularQueue.enQueue(3); // 返回 true circularQueue.enQueue(4); // 返回 false,队列已满 circularQueue.Rear(); // 返回 3 circularQueue.isFull(); // 返回 true circularQueue.deQueue(); // 返回 true circularQueue.enQueue(4); // 返回 true circularQueue.Rear(); // 返回 4
提示:
- 所有的值都在 0 至 1000 的范围内;
- 操作数将在 1 至 1000 的范围内;
- 请不要使用内置的队列库。
一. 实现思路
通过
数组
和队头队尾指针
来实现一个循环队列
因为环形结构比较难实现,所以通过线性结构和指针来实现
- 创建:新建一个数组,初始化两个指针,用来指定队首
head
和队尾tail
的位置 - 添加元素:队尾指针
tail
加一(因为是循环数组所以应该是(tail + 1) % size
),将指针对应的位置设置数据 - 删除元素:队头指针
head
加一(因为是循环数组所以应该是(head + 1) % size
),指针位置数据不用变化,因为取数据只靠指针,而添加数据的时候需要将数据覆盖就可以了 - 获取第一项:根据
队头指针
获取元素 - 获取最后一项:根据
队尾指针
获取元素
二. 代码实现
class MyCircularQueue {
private int[] data;
private int head;
private int tail;
private int size;
/** 初始化数据结构,并规定队列大小k */
public MyCircularQueue(int k) {
data = new int[k];
head = -1;
tail = -1;
size = k;
}
/** 在队列插入一项,并返回插入是否成功 */
public boolean enQueue(int value) {
if (isFull() == true) {
return false;
}
if (isEmpty() == true) {
head = 0;
}
tail = (tail + 1) % size;
data[tail] = value;
return true;
}
/** 从队列删除一项,并返回删除是否成功 */
public boolean deQueue() {
if (isEmpty() == true) {
return false;
}
if (head == tail) {
head = -1;
tail = -1;
return true;
}
head = (head + 1) % size;
return true;
}
/** 获取队列第一项 */
public int Front() {
if (isEmpty() == true) {
return -1;
}
return data[head];
}
/** 获取队列最后一项 */
public int Rear() {
if (isEmpty() == true) {
return -1;
}
return data[tail];
}
/** 检查队列是否为空 */
public boolean isEmpty() {
return head == -1;
}
/** 检查队列是否已满 */
public boolean isFull() {
return ((tail + 1) % size) == head;
}
}