622. 设计循环队列
https://blog.csdn.net/Galaxy_n/article/details/115978544
typedef struct { int *arrs; int front; int rear; int size; } MyCircularQueue; /* 判断队列是否为空 */ bool myCircularQueueIsEmpty(MyCircularQueue* obj) { return obj->front == obj->rear; } /* 判断队列是否满了 */ bool myCircularQueueIsFull(MyCircularQueue* obj) { int rearNext = obj->rear + 1; if (rearNext == obj->size + 1) { rearNext = 0; } return rearNext == obj->front; } MyCircularQueue* myCircularQueueCreate(int k) { MyCircularQueue *obj = malloc(sizeof(MyCircularQueue)); obj->arrs = (int *)malloc(sizeof(int) * (k + 1)); obj->front = 0; obj->rear = 0; obj->size = k; return obj; } /* 插入元素入队(尾插) */ bool myCircularQueueEnQueue(MyCircularQueue* obj, int value) { if (myCircularQueueIsFull(obj)) { return false; } obj->arrs[obj->rear++] = value; if (obj->rear == obj->size + 1) { obj->rear = 0; } return true; } /* 从队列中删除元素 */ bool myCircularQueueDeQueue(MyCircularQueue* obj) { if (myCircularQueueIsEmpty(obj)) { return false; } obj->front++; // 要考虑“循环” if (obj->front == obj->size + 1) { obj->front = 0; } return true; } /* 取队列首元素 */ int myCircularQueueFront(MyCircularQueue* obj) { if (myCircularQueueIsEmpty(obj)) { return -1; } return obj->arrs[obj->front]; } /* 取队列尾元素 */ int myCircularQueueRear(MyCircularQueue* obj) { if (myCircularQueueIsEmpty(obj)) { return -1; } int rearPre = obj->rear - 1; if (rearPre == -1) { rearPre = obj->size; } return obj->arrs[rearPre]; } void myCircularQueueFree(MyCircularQueue* obj) { free(obj->arrs); 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); */