LeetCode622循环队列C语言实现
c语言一般是10表示true false,所以有一点点不习惯。
这道题需要注意的点。开始的时候front=1,back=0。
这样enqueue和dequeue就不用多余的判断了,
只有自己尝试写过才知道这样赋初值的巧妙之处。
再有就是不要尝试用front和back的关系判满或者空,真的很麻烦,写一堆判断还不如加一个size的变量。
typedef struct {int back, front;int size;int capacity;int q[1000];} MyCircularQueue;/** Initialize your data structure here. Set the size of the queue to be k. */MyCircularQueue* myCircularQueueCreate(int k) {MyCircularQueue* obj;obj=(MyCircularQueue*)malloc(sizeof(MyCircularQueue));obj->capacity=k;for(int i=k-1;i>=0;i--) obj->q[i]=-1;obj->back=0;obj->front=1;obj->size=0;return obj;}/** Get the front item from the queue. */int myCircularQueueFront(MyCircularQueue* obj) {return obj->q[obj->front];}/** Get the last item from the queue. */int myCircularQueueRear(MyCircularQueue* obj) {return obj->q[obj->back]; }/** Checks whether the circular queue is empty or not. */bool myCircularQueueIsEmpty(MyCircularQueue* obj) {return obj->size==0;}/** Checks whether the circular queue is full or not. */bool myCircularQueueIsFull(MyCircularQueue* obj) {return obj->size==obj->capacity;}/** Insert an element into the circular queue. Return true if the operation is successful. */bool myCircularQueueEnQueue(MyCircularQueue* obj, int value) {if(myCircularQueueIsFull(obj)) return false;else{obj->back++;obj->size++;if(obj->back==obj->capacity) obj->back=0;obj->q[obj->back]=value;return true;}}/** Delete an element from the circular queue. Return true if the operation is successful. */bool myCircularQueueDeQueue(MyCircularQueue* obj) {if(myCircularQueueIsEmpty(obj)) return false;else{obj->q[obj->front]=-1;obj->front++;if(obj->front==obj->capacity) obj->front=0;obj->size--;return true;}}void myCircularQueueFree(MyCircularQueue* obj) {free(obj);}