题集-数组实现循环队列

题集-数组实现循环队列_第1张图片


#define allocator_may_return_null

typedef struct {
     int front;
     int rear;
     int k;
     int *a;
} MyCircularQueue;


MyCircularQueue* myCircularQueueCreate(int k) 
{
    MyCircularQueue * obj = (MyCircularQueue*)malloc(sizeof(MyCircularQueue));
    obj->a = (int*)malloc(sizeof(int)*(k+1));
     obj->k = k;
     obj->front = 0;
     obj->rear = 0;
     return obj;
}
bool myCircularQueueIsEmpty(MyCircularQueue* obj) {
     return obj->rear == obj->front;
}


bool myCircularQueueIsFull(MyCircularQueue* obj) {
     return (obj->rear+1)%(obj->k+1) == obj->front;
}


bool myCircularQueueEnQueue(MyCircularQueue* obj, int value) {
     if(myCircularQueueIsFull(obj))
        return false;
    else 
    {
        obj->a[obj->rear] = value;
        obj->rear = (obj->rear+1)%(obj->k+1);
        return true;
    }
}

bool myCircularQueueDeQueue(MyCircularQueue* obj) {
    if(!myCircularQueueIsEmpty(obj))
    {
       obj->front = (obj->front+1)%(obj->k+1);
       return true;
    }
    else return false;
}

int myCircularQueueFront(MyCircularQueue* obj) {
    if(!myCircularQueueIsEmpty(obj))
    {
        return obj->a[obj->front];
    }
    else return -1;
}

int myCircularQueueRear(MyCircularQueue* obj) {
    if(!myCircularQueueIsEmpty(obj))
    {
        return obj->a[(obj->rear+obj->k)%(obj->k+1)];
    }
    else return -1;
}



void myCircularQueueFree(MyCircularQueue* obj) {
     free(obj->a);
     obj->a = NULL;
     free(obj);
     obj = NULL;
}

你可能感兴趣的:(c++,数据结构)