赞
踩
实现循环队列可以用数组或者是链表,但是因为链表无法找到前一个元素,所以在进行删除时,需要遍历数据效率比较低,而数组无论时插入或者删除效率都比较高,所以我们选择数组。
创建结构体
初始化
检查队列是否为空
检查队列是否已满
插入元素
删除元素
获取队首元素
获取队尾元素
- typedef struct {
- int* a;//数组指针
- int front;
- int tail;
- int k;//队列长度
-
- } MyCircularQueue;
-
-
- MyCircularQueue* myCircularQueueCreate(int k) {
- MyCircularQueue* obj=(MyCircularQueue*)malloc(sizeof(MyCircularQueue));
- obj->a=(int*)malloc((k+1)*sizeof(int));
- obj->front=obj->tail=0;
- obj->k=k;
- return obj;
-
- }
- bool myCircularQueueIsEmpty(MyCircularQueue* obj) {
- assert(obj);
- return obj->front==obj->tail;
-
- }
- bool myCircularQueueIsFull(MyCircularQueue* obj) {
- assert(obj);
- return (obj->tail+1)%(obj->k+1)==(obj->front);
-
- }
-
- bool myCircularQueueEnQueue(MyCircularQueue* obj, int value) {
- assert(obj);
- if(myCircularQueueIsFull(obj))
- {
- return false;
- }
- obj->a[obj->tail++]=value;
- obj->tail%=(obj->k+1);
- return true;
- }
-
- bool myCircularQueueDeQueue(MyCircularQueue* obj) {
- assert(obj);
- if(myCircularQueueIsEmpty(obj))
- {
- return false;
- }
- obj->front++;
- obj->front%=(obj->k+1);
- return true;
-
- }
-
- int myCircularQueueFront(MyCircularQueue* obj) {
- assert(obj);
- if(myCircularQueueIsEmpty(obj))
- {
- return -1;
- }
- else
- {
- return obj->a[obj->front];
- }
-
- }
-
- int myCircularQueueRear(MyCircularQueue* obj) {
- assert(obj);
- if(myCircularQueueIsEmpty(obj))
- {
- return -1;
- }
- else
- {
- return obj->a[(obj->tail+obj->k)%(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);
- */

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。