1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > LeetCode622循环队列C语言实现

LeetCode622循环队列C语言实现

时间:2018-10-06 07:17:42

相关推荐

LeetCode622循环队列C语言实现

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);}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。