C language single chain queue representation and implementation of examples

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

1. Overview:

Queue In C language refers to a first-in-first-out linear table. 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).

while Single-stranded queues use linked lists as basic data results, so there is no pseudo-overflow problem and there is no limit to queue length. But the insertion and read times can be expensive

2. Example code:



typedef struct QNode
{
 QElemType data;
 struct QNode *next;
}QNode,*QueuePtr;
typedef struct
{
 QueuePtr front,rear; 
}LinkQueue;

void InitQueue(LinkQueue *Q)
{ 
 Q->front=Q->rear=malloc(sizeof(QNode));
 if(!Q->front)
  exit(OVERFLOW);
 Q->front->next=NULL;
}
void DestroyQueue(LinkQueue *Q)
{ 
 while(Q->front)
 {
  Q->rear=Q->front->next;
  free(Q->front);
  Q->front=Q->rear;
 }
}
void ClearQueue(LinkQueue *Q)
{ 
 QueuePtr p,q;
 Q->rear=Q->front;
 p=Q->front->next;
 Q->front->next=NULL;
 while(p)
 {
  q=p;
  p=p->next;
  free(q);
 }
}
Status QueueEmpty(LinkQueue Q)
{ 
 if(Q.front->next==NULL)
  return TRUE;
 else
  return FALSE;
}
int QueueLength(LinkQueue Q)
{ 
 int i=0;
 QueuePtr p;
 p=Q.front;
 while(Q.rear!=p)
 {
  i++;
  p=p->next;
 }
 return i;
}
Status GetHead_Q(LinkQueue Q,QElemType *e)
{ 
 QueuePtr p;
 if(Q.front==Q.rear)
  return ERROR;
 p=Q.front->next;
 *e=p->data;
 return OK;
}
void EnQueue(LinkQueue *Q,QElemType e)
{ 
 QueuePtr p= (QueuePtr)malloc(sizeof(QNode));
 if(!p) 
  exit(OVERFLOW);
 p->data=e;
 p->next=NULL;
 Q->rear->next=p;
 Q->rear=p;
}
Status DeQueue(LinkQueue *Q,QElemType *e)
{ 
 QueuePtr p;
 if(Q->front==Q->rear)
  return ERROR;
 p=Q->front; 
 *e=p->data;
 Q->front=p->next; 
 if(Q->rear==p)
  Q->rear=Q->front;
 free(p);
 return OK;
}
void QueueTraverse(LinkQueue Q,void(*vi)(QElemType))
{ 
 QueuePtr p;
 p=Q.front->next;
 while(p)
 {
  vi(p->data);
  p=p->next;
 }
 printf("n");
}

Related articles: