用数组实现循环队列
题目:622. 设计循环队列 - 力扣(LeetCode)
分析
循环队列,队列满则不能再插入数据,队列为空则不能再出数据。
多开一个空间方便区分队列为空和队列为满的情况。
如果要存K个数据只开K个空间,那么队列空和满都是rear==front(这里的front指向队头,rear指向队尾);所以开K+1个空间让rear指向队尾的下一个,rear==front则队列空,rear+1==front则队列满了。
要实现循环,借助取模来操作。
typedef struct {int *a;int k;int front;//指向头int rear;//指向尾的下一个} MyCircularQueue;MyCircularQueue* myCircularQueueCreate(int k) {MyCircularQueue*p=(MyCircularQueue*)malloc(sizeof(MyCircularQueue));p->a=malloc(sizeof(int)*(k+1));//为数组开K+1个空间,多开一个方便判空和满p->k=k;p->front=p->rear=0;return p;
}bool myCircularQueueIsEmpty(MyCircularQueue* obj) {return obj->front==obj->rear;
}bool myCircularQueueIsFull(MyCircularQueue* obj) {return ((obj->rear+1)%(obj->k+1))==obj->front;
}
bool myCircularQueueEnQueue(MyCircularQueue* obj, int value) {if(myCircularQueueIsFull(obj)){return false;}obj->a[obj->rear++]=value;obj->rear=(obj->rear)%(obj->k+1);return true;
}bool myCircularQueueDeQueue(MyCircularQueue* obj) {if(myCircularQueueIsEmpty(obj)){return false;}obj->front++;obj->front=(obj->front)%(obj->k+1);return true;
}int myCircularQueueFront(MyCircularQueue* obj) {if(myCircularQueueIsEmpty(obj)){return -1;}return obj->a[obj->front];
}int myCircularQueueRear(MyCircularQueue* obj) {if(myCircularQueueIsEmpty(obj)){return -1;}return obj->a[((obj->rear-1)+(obj->k+1))%(obj->k+1)];
}void myCircularQueueFree(MyCircularQueue* obj) {free(obj->a);free(obj);
}/*** Your MyCircularQueue struct will be instantiated and called as such:* MyCircularQueue* obj = myCircularQueueCreate(k);* bool param_1 = myCircularQueueEnQueue(obj, value);* bool param_2 = myCircularQueueDeQueue(obj);* int param_3 = myCircularQueueFront(obj);* int param_4 = myCircularQueueRear(obj);* bool param_5 = myCircularQueueIsEmpty(obj);* bool param_6 = myCircularQueueIsFull(obj);* myCircularQueueFree(obj);
*/