循环队列的实现
程序员文章站
2022-06-06 22:31:29
...
所谓循环队列,就是可以不断地往进存数据,我们首先想到的可能是数组实现,但是其实是其实使用数组是存在问题的,下面请看下图。
首先如果数组下标由0-4的位置都存了数据,现在把0-3位置的数据移出去,那么下次存入数据时,肯定是从下标为4的下一个位置开始存数据,这样就造成了空间的大量浪费。且front和rear指针并不能判断当前数组是否为空还是满了。
所以,引用容量和大小来进行判定,如果size0,当前为空,如果sizecapacity说明已经存满了。
下面贴出详细代码:
class MyCircularQueue {
public:
int size;//定义大小
int capacity;//定义容量
int* array;//定义一个数组
int front;
int rear;
/** Initialize your data structure here. Set the size of the queue to be k. */
MyCircularQueue(int k) {
array=(int*)malloc(sizeof(int)*k);
size=0;
capacity=k;
front=0;
rear=0;
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
bool enQueue(int value) {
if(size>=capacity)
{
return false;
}
array[rear]=value;
rear=(rear+1)%capacity;//如果最后一个数组下标的位置已经存入 了数据,那么久循环
size++;
return true;
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
bool deQueue() {
if(size<=0)
{
return false;
}
size--;
front=(front+1)%capacity;
return true;
}
/** Get the front item from the queue. */
int Front() {
if(size<=0)
{
return -1;}
return array[front];
}
/** Get the last item from the queue. */
int Rear() {
if(size<=0)
{
return -1;
}
int index=(rear-1+capacity)%capacity;
return array[index];
}
/** Checks whether the circular queue is empty or not. */
bool isEmpty() {
return size==0;
}
/** Checks whether the circular queue is full or not. */
bool isFull() {
return size==capacity;
}
};
上一篇: 使用Navicat连接阿里云ECS服务器上的MySQL数据库
下一篇: 模式匹配(二十)