沈阳做网站最好的公司/经典软文案例
设计循环队列
题目描述
循环队列是一种线性数据结构,其操作表现基于 FIFO(先进先出)原则并且队尾被连接在队首之后以形成一个循环。它也被称为“环形缓冲器”。
循环队列的一个好处是我们可以利用这个队列之前用过的空间。在一个普通队列里,一旦一个队列满了,我们就不能插入下一个元素,即使在队列前面仍有空间。但是使用循环队列,我们能使用这些空间去存储新的值。
你的实现应该支持如下操作:
MyCircularQueue(k): 构造器,设置队列长度为 k 。
Front: 从队首获取元素。如果队列为空,返回 -1 。
Rear: 获取队尾元素。如果队列为空,返回 -1 。
enQueue(value): 向循环队列插入一个元素。如果成功插入则返回真。
deQueue(): 从循环队列中删除一个元素。如果成功删除则返回真。
isEmpty(): 检查循环队列是否为空。
isFull(): 检查循环队列是否已满。
示例:
MyCircularQueue circularQueue = new MycircularQueue(3); // 设置长度为3circularQueue.enQueue(1); // 返回truecircularQueue.enQueue(2); // 返回truecircularQueue.enQueue(3); // 返回truecircularQueue.enQueue(4); // 返回false,队列已满circularQueue.Rear(); // 返回3circularQueue.isFull(); // 返回truecircularQueue.deQueue(); // 返回truecircularQueue.enQueue(4); // 返回truecircularQueue.Rear(); // 返回4
循环队列的创建的思想:
- 用数组实现循环队列而不用链表实现循环队列的原因是链表比较难实现删除最后一个元素,以及在任意位置前插入或删除元素。
- 在向循环队列中插入元素时必须保证空出一个位置,为方便判断循坏队列是否已满,判满的方式为(obj->_rear+1)%obj->_n == obj->_front,若相等则队列为空,反之则非满。判空则只需比较obj->_rear == obj->_front,相等为空,反之非空。
代码实现
typedef struct {int* _array;int _n;int _front;int _rear; } MyCircularQueue;/** Initialize your data structure here. Set the size of the queue to be k. */MyCircularQueue* myCircularQueueCreate(int k) {//初始化循环队列MyCircularQueue* queue = (MyCircularQueue*)malloc(sizeof(MyCircularQueue));queue->_array = (int*)malloc(sizeof(int)*(k+1));//给数组申请空间queue->_n = k+1;queue->_front = 0;queue->_rear = 0;return queue;}/** Checks whether the circular queue is full or not. */bool myCircularQueueIsFull(MyCircularQueue* obj) {return (obj->_rear+1)%obj->_n == obj->_front ? true : false; }/** Checks whether the circular queue is empty or not. */bool myCircularQueueIsEmpty(MyCircularQueue* obj) {return obj->_front == obj->_rear ? true : false;}/** Insert an element into the circular queue. Return true if the operation is successful. */bool myCircularQueueEnQueue(MyCircularQueue* obj, int value) {if(myCircularQueueIsFull(obj) == true)return false;obj->_array[obj->_rear++] = value;//添加元素,_rear++//若尾指针加到数组的最后,若队列未满,再入元素时只需让_rear指向数组开始位置obj->_rear %= obj->_n;return true;}/** Delete an element from the circular queue. Return true if the operation is successful. */bool myCircularQueueDeQueue(MyCircularQueue* obj) {if(myCircularQueueIsEmpty(obj) == true)return false;++obj->_front;return true;}/** Get the front item from the queue. */int myCircularQueueFront(MyCircularQueue* obj) {if(myCircularQueueIsEmpty(obj) == true)return -1;return obj->_array[obj->_front];}/** Get the last item from the queue. */int myCircularQueueRear(MyCircularQueue* obj) {if(myCircularQueueIsEmpty(obj) == true)return -1;else{//若_rear重新回到数组起始位置时,返回队列最后一个元素只能返回数组中下标n-1的元素而不能返回下标为_rear-1的元素,否则数组访问越界if(obj->_rear == 0)return obj->_array[obj->_n-1];elsereturn obj->_array[obj->_rear-1]; }}void myCircularQueueFree(MyCircularQueue* obj) {free(obj->_array);obj->_front = 0;obj->_rear = 0;free(obj); }