web123456

Loop queue (C language)

  • #include<>
  • #include<>
  • #include<>
  • #include""
  • void Init(PQueue pq) {
  • assert(pq!=NULL);
  • pq->base = (ELEM_TYPE*)malloc(MAX_SIZE * sizeof(ELEM_TYPE));
  • assert(pq->base != NULL);
  • pq->front = 0;
  • pq->rear = 0;
  • }
  • bool Push(PQueue pq, ELEM_TYPE val) {
  • assert(pq != NULL);
  • if (IsFull(pq)) {
  • return false;
  • }
  • pq->base[pq->rear] = val;
  • pq->rear = (pq->rear + 1) % MAX_SIZE;
  • return true;
  • }
  • bool Pop(PQueue pq) {
  • assert(pq != NULL);
  • if (IsEmpty(pq)) {
  • return false;
  • }
  • pq->front=(pq->front+1)%MAX_SIZE;
  • return true;
  • }
  • bool Top(PQueue pq, ELEM_TYPE* rtval) {
  • assert(pq != NULL);
  • if (IsEmpty(pq)) {
  • return false;
  • }
  • *rtval = pq->base[pq->front];
  • return true;
  • }
  • bool IsEmpty(PQueue pq) {
  • assert(pq != NULL);
  • return pq->front == pq->rear;
  • }
  • bool IsFull(PQueue pq) {
  • assert(pq != NULL);
  • return (pq->rear + 1) % MAX_SIZE == pq->front;
  • }
  • int Get_length(PQueue pq) {
  • assert(pq != NULL);
  • int count= (pq->rear - pq->front + MAX_SIZE) % MAX_SIZE;//The first is to prevent negative numbers from appearing, and the second is to prevent positive numbers from adding more
  • return count;
  • }
  • void Clear(PQueue pq) {
  • assert(pq != NULL);
  • pq->front = pq->rear = 0;
  • }
  • void Destory(PQueue pq) {
  • assert(pq != NULL);
  • free(pq->base);
  • pq->front = pq->rear = 0;
  • }
  • void show(PQueue pq) {
  • assert(pq != NULL);
  • for (int i = pq->front;i!= pq->rear;i=(i+1)%MAX_SIZE) {
  • printf("%5d",pq->base[i]);
  • }
  • printf("\n");
  • }