C language circular queue representation and implementation examples

  • 2020-04-02 02:27:46
  • OfStack

1. Overview:

Queue In C language is a first-in-first-out linear table data structure. In the concrete application commonly used linked list or array to achieve. Queues are only allowed to be inserted in the back (called rear) and deleted in the front (called front).

Circular queues are easier to prevent pseudo-overflow, but the queue size is fixed.

2. Example code:



#define MAX_QSIZE 5 
typedef struct
{
 QElemType *base; 
 int front; 
 int rear; 
}SqQueue;

void InitQueue(SqQueue *Q)
{ 
 Q->base=malloc(MAX_QSIZE*sizeof(QElemType));
 if(!Q->base) 
  exit(OVERFLOW);
 Q->front=Q->rear=0;
}
void DestroyQueue(SqQueue *Q)
{ 
 if(Q->base)
  free(Q->base);
 Q->base=NULL;
 Q->front=Q->rear=0;
}
void ClearQueue(SqQueue *Q)
{ 
 Q->front=Q->rear=0;
}
Status QueueEmpty(SqQueue Q)
{ 
 if(Q.front==Q.rear) 
  return TRUE;
 else
  return FALSE;
}
int QueueLength(SqQueue Q)
{ 
 return(Q.rear-Q.front+MAX_QSIZE)%MAX_QSIZE;
}
Status GetHead(SqQueue Q,QElemType *e)
{ 
 if(Q.front==Q.rear) 
  return ERROR;
 *e=Q.base[Q.front];
 return OK;
}
Status EnQueue(SqQueue *Q,QElemType e)
{ 
 if((Q->rear+1)%MAX_QSIZE==Q->front) 
  return ERROR;
 Q->base[Q->rear]=e;
 Q->rear=(Q->rear+1)%MAX_QSIZE;
 return OK;
}
Status DeQueue(SqQueue *Q,QElemType *e)
{ 
 if(Q->front==Q->rear) 
  return ERROR;
 *e=Q->base[Q->front];
 Q->front=(Q->front+1)%MAX_QSIZE;
 return OK;
}
void QueueTraverse(SqQueue Q,void(*vi)(QElemType))
{ 
 int i;
 i=Q.front;
 while(i!=Q.rear)
 {
  vi(Q.base[i]);
  i=(i+1)%MAX_QSIZE;
 }
 printf("n");
}

Related articles: