15.循环队列
* 解题思路: 通过一个定长数组实现循环队列 入队:首先要判断队列是否已满,再进行入队的操作,入队操作需要考虑索引循环的问题,当索引越界,需要让它变成最小值 出队:首先要判断队列是否为空,再进行出队操作,出队也需要考虑索引循环的问题 判空: 队头 == 队尾 判满: 队尾 + 1 == 队头 */
typedef struct
{
int*_arr;
int _front;
int _rear;
int k;
} MyCircularQueue;
bool myCircularQueueIsEmpty(MyCircularQueue* obj)//是否为空
{
if(obj->_front==obj->_rear)
{
return true;
}
else
{
return false;
}
}
bool myCircularQueueIsFull(MyCircularQueue* obj)
{
if( (obj->_rear+1)%(obj->k+1)==obj->_front)
{
return true;
}
else
{
return false;
}
}
MyCircularQueue* myCircularQueueCreate(int k)
{
MyCircularQueue*Queue=(MyCircularQueue*)malloc(sizeof(MyCircularQueue));
if(Queue==NULL)
{
perror("malloc");
exit(-1);
}
int*arr=(int*)malloc(sizeof(int)*(k+1));
if(arr==NULL)
{
perror("malloc");
exit(-1);
}
Queue->_arr=arr;
Queue->_front=Queue->_rear=0;
Queue->k=k;
return Queue;
}
bool myCircularQueueEnQueue(MyCircularQueue* obj, int value) //入队
{
if(myCircularQueueIsFull(obj)==false )
{
obj->_arr[obj->_rear]=value;
obj->_rear++;
obj->_rear= obj->_rear%(obj->k+1);
return true;
}
else
{
return false;
}
}
bool myCircularQueueDeQueue(MyCircularQueue* obj) //出队
{
if(myCircularQueueIsEmpty(obj)==false )
{
obj->_front++;
obj->_front= obj->_front%(obj->k+1);
return true;
}
else
{
return false;
}
}
int myCircularQueueFront(MyCircularQueue* obj)
{
if(myCircularQueueIsEmpty( obj)==true)
{
return -1;
}
else
{
return obj->_arr[obj->_front];
}
}
int myCircularQueueRear(MyCircularQueue* obj)
{
if(myCircularQueueIsEmpty( obj)==true)
{
return -1;
}
else
{
return obj->_arr[(obj->_rear+obj->k)%(obj->k+1)];
}
}
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);
*/