typedef struct { int *arr; int front; int tail; int size; } MyCircularQueue; MyCircularQueue* myCircularQueueCreate(int k) { MyCircularQueue *obj = (MyCircularQueue *)malloc(sizeof(MyCircularQueue)); obj->arr = (int *)malloc((k+1) * sizeof(int)); obj->front = 0; obj->tail = 0; obj->size = k+1; return obj; } bool myCircularQueueEnQueue(MyCircularQueue* obj, int value) { if (obj->front == ((obj->tail + 1) % obj->size)) return false; obj->arr[(obj->tail)] = value; obj->tail = ((obj->tail) + 1) % obj->size; return true; } bool myCircularQueueDeQueue(MyCircularQueue* obj) { if (obj->front == obj->tail) return false; (obj->front) = ((obj->front) + 1) % obj->size; return true; } int myCircularQueueFront(MyCircularQueue* obj) { if (obj->front == obj->tail) return -1; return obj->arr[obj->front]; } int myCircularQueueRear(MyCircularQueue* obj) { if (obj->front == obj->tail) return -1; int tmp = (obj->tail - 1 + obj->size) % obj->size; return obj->arr[tmp]; } bool myCircularQueueIsEmpty(MyCircularQueue* obj) { return (obj->front == obj->tail); } bool myCircularQueueIsFull(MyCircularQueue* obj) { return obj->front == ((obj->tail + 1) % obj->size); } void myCircularQueueFree(MyCircularQueue* obj) { free(obj->arr); 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); */
记录下做题时候碰到的一些问题:
front指向队头元素,tail指向的则是队尾后一个元素(指示的是待插入的位置)。
由于是循环队列,实现的是时候注意取模。
取队尾元素的时候要注意不能对负数%。
(obj->tail - 1 + obj->size) % obj->size 标签:obj,队列,MyCircularQueue,C语言,int,tail,循环,front,return From: https://www.cnblogs.com/leomehhh/p/17167765.html