队列的性质

先进先出

简单队列

  • 相对简单,下面给出代码;
typedef struct {
    int *que;   //内存,相当于数组
    int end;    //尾指针
    int begin;   //前指针
    int count;   //队列的当前容量
} MaxQueue;

MaxQueue* maxQueueCreate() {    //队列的初始化;
    MaxQueue*obj=(MaxQueue*)malloc(sizeof(MaxQueue));
    obj->que=(int*)malloc(sizeof(int)*10000);

    obj->begin=0;
    obj->end=0;
    obj->count=0;
    return obj;
}

void maxQueuePush_back(MaxQueue* obj, int value) {  //插入操作,从尾部进行
    obj->que[obj->end]=value;
    obj->end++;
    obj->count++;

}

int maxQueuePop_front(MaxQueue* obj) {   //删除操作,从队列头部进行
    int ret=-1;
    if(obj->count == 0) return -1;
    ret=obj->que[obj->begin];
    obj->begin++;
    obj->count--;
    return ret;
}

void maxQueueFree(MaxQueue* obj) {   //释放队列
    free(obj);
}

循环队列

  • 基本操作和简单队列相似,就是插入和删除操作进行了优化;下面给出完整代码;
typedef struct {
    int *base;
    int rear; //尾部指针
    int front; //头部指针
    int count;  //队列当前容量
    int backet;  //队列总容量
} 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->base=(int *)malloc(sizeof(int)*k);
    obj->rear=-1;
    obj->front=-1;
    obj->count=0;
    obj->backet=k;  //队列总容量
    return obj;
}

/** Insert an element into the circular queue. Return true if the operation is successful. */
bool myCircularQueueEnQueue(MyCircularQueue* obj, int value) { //插入操作
  if(obj->count==obj->backet) {  //判断队列是否满了
      return false;
  }
  if(obj->count==0) {   //如果是第一的数
      obj->rear=obj->front=0;
      obj->base[obj->rear]=value;
  }
  else obj->base[obj->rear=(obj->rear+1)%obj->backet]=value;
  
  obj->count++;

  return true;
}

/** Delete an element from the circular queue. Return true if the operation is successful. */
bool myCircularQueueDeQueue(MyCircularQueue* obj) {   //删除操作
  if(obj->count==0){
      return false;
  }
 if(obj->count==0){  //判断是否为空队列
     obj->rear=obj->front=0;
 }
 else obj->front=(obj->front+1) % obj->backet;
 obj->count--;
 return true;
}


int myCircularQueueFront(MyCircularQueue* obj) {  //获取头部元素
  if(obj->count==0){
      return -1;
  }
  return obj->base[obj->front];
}


int myCircularQueueRear(MyCircularQueue* obj) {  //获取尾部元素
  if(obj->count==0){
      return -1;
  }
  return obj->base[(obj->rear)];
}

/** Checks whether the circular queue is empty or not. */
bool myCircularQueueIsEmpty(MyCircularQueue* obj) { //判断是否为空
  if(obj->count==0) return true;
  return false;
}

/** Checks whether the circular queue is full or not. */
bool myCircularQueueIsFull(MyCircularQueue* obj) { //判断是否满了
  if(obj->count==obj->backet) return true;
  return false;
}

void myCircularQueueFree(MyCircularQueue* obj) { 释放队列
     free(obj->base);
    free(obj);
    
   
}

谢谢浏览;