队列:
只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出FIFO(FirstIn First Out)。 入队列:进行插入操作的一端称为队尾(Tail/Rear)出队列:进行删除操作的一端称为队头。
循环队列:
- 将队头和队尾以某种方式关联起来,在逻辑上达到循环一圈的目的。
- 力扣上有原题,我是按照力扣上的题目要求写的。力扣622–设计循环队列
思路:
- 通过数组作为底层结构。
- 定义一个头指针,指向第一个元素。
- 定义一个尾指针,永远指向最后一个数据的下一个位置。
- 当要添加元素时,直接将元素插在尾指针位置,然后尾指针后移一步。
- 当要删除元素时,判断元素位置在头指针位置、尾位置、还是中间位置。头位置直接将头指针后移一步。尾位置将尾指针前移一步。
- 重要:循环队列里最奇妙的是指针走到数据终点如何让他再次从头走得问题。在这里,可以通过(尾指针下标 + 1 )% 数组长度。
实现
class MyCircularQueue {
//定义一个数组
public int[] circleArray;
//头指针
public int head;
//尾指针
public int tail;
//元素数量
public int count;
/** Initialize your data structure here. Set the size of the queue to be k. */
public MyCircularQueue(int k) {
this.circleArray = new int[k + 1];
this.count = 0;
this.head = 0;
this.tail = 0;
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
//插入元素
public boolean enQueue(int value) {
if (isFull()) {
//队列满,返回
return false;
} else {
//队尾元素赋值
circleArray[tail] = value;
//元素数量+1
count++;
//队尾指针+1
tail = (tail + 1) % circleArray.length;
}
return true;
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
//删除队头元素
public boolean deQueue() {
if (isEmpty()) {
return false;
} else {
circleArray[head] = 0;
head = (head + 1) % circleArray.length;
count--;
//circleArray[tail] = 0;
//tail = (tail - 1) % circleArray.length;
}
return true;
}
/** Get the front item from the queue. */
//队首获取元素
public int Front() {
if (isEmpty()) {
return -1;
} else {
return circleArray[head];
}
}
/** Get the last item from the queue. */
//获取队尾元素
public int Rear() {
if (isEmpty()) {
return -1;
} else {
if (tail == 0) {
return circleArray[circleArray.length - 1];
} else {
return circleArray[tail - 1];
}
}
}
/** Checks whether the circular queue is empty or not. */
public boolean isEmpty() {
return head == tail;
}
/** Checks whether the circular queue is full or not. */
public boolean isFull() {
return (tail + 1) % circleArray.length == head;
}
//为了方便自己调试而写的打印方法
public void display() {
int a = head;
int b = tail;
while (a != b) {
System.out.print(circleArray[a]+" ");
a = (a + 1) % circleArray.length;
}
System.out.println();
}
}