🌈个人主页:羽晨同学
💫个人格言:“成为自己未来的主人~”
思路:
我们在这里采用的是用数组的形式实现循环链表,我认为这个用数组是更为简单的,我们只需要控制下标就可以实现循环链表的效果。具体实现代码如下:
typedef struct {
int*a;
int front;
int rear;
int size;
int capacity;
} MyCircularQueue;
MyCircularQueue* myCircularQueueCreate(int k) {
MyCircularQueue*obj=(MyCircularQueue*)malloc(sizeof(MyCircularQueue));
obj->a=(int*)malloc(sizeof(int)*(k+1));
obj->front=0;
obj->rear=0;
obj->size=0;
obj->capacity=k+1;
return obj;
}
bool myCircularQueueEnQueue(MyCircularQueue* obj, int value)
{
if((obj->rear+1)%(obj->capacity)==obj->front)
{
return false;
}
else
{
obj->a[obj->rear]=value;
//4
obj->rear=(obj->rear+1)%(obj->capacity);
}
obj->size++;
return true;
}
bool myCircularQueueDeQueue(MyCircularQueue* obj)
{
if(obj->front==obj->rear)
{
return false;
}
else{
obj->front=(obj->front+1)%(obj->capacity);
}
obj->size--;
return true;
}
int myCircularQueueFront(MyCircularQueue* obj)
{
if(obj->size>=1)
{
return obj->a[obj->front];
}
else
{
return -1;
}
}
int myCircularQueueRear(MyCircularQueue* obj)
{
if(obj->size>=1)
{
return obj->a[(obj->rear-1+obj->capacity)%(obj->capacity)];
}
else
return -1;
}
bool myCircularQueueIsEmpty(MyCircularQueue* obj)
{
return obj->front==obj->rear;
}
bool myCircularQueueIsFull(MyCircularQueue* obj)
{
return (obj->rear+1)%(obj->capacity)==obj->front;
}
void myCircularQueueFree(MyCircularQueue* obj)
{
free(obj->a);
obj->a=NULL;
obj->front=obj->rear=obj->size=obj->capacity=0;
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);
*/