1. Overview:
C-language queues (queue) is a first-out (FIFO, first-in-first-out) linear table data structure. In a specific application, a linked list or array is usually used for implementation. Queues allow insertions only at the back end (called rear) and are removed at the front end (called the front).
Loop queues can be simpler to prevent pseudo overflow occurrences, but the queue size is fixed.
2. Instance code:
/* Queued sequential storage structure (loop queue)/#define MAX_QSIZE 5/* Maximum Queue Length +1/typedef struct {Qelemtype *base; * Initialized dynamic allocation storage space/int front ; /* head pointer, if the queue is not empty, point to the queue head element/int rear;
/* tail pointer, if the queue is not empty, point to the end of the queue element next position * *}SQQUEUE;
/* The basic operation of the cyclic queue (9)/void Initqueue (Sqqueue *q) {/* Constructs an empty queue Q/Q->base=malloc (max_qsize*sizeof (Qelemtype)); if (!
Q->base)/* Storage allocation failure/exit (OVERFLOW);
q->front=q->rear=0;
} void Destroyqueue (Sqqueue *q) {/* Destroy queue Q,q no longer exists */if (q->base) free (q->base);
q->base=null;
q->front=q->rear=0;
} void Clearqueue (Sqqueue *q) {/* Clear Q to empty queue */q->front=q->rear=0;}
Status queueempty (Sqqueue q) {/* If queue Q is empty queue, returns true; False/if (q.front==q.rear)/* Queue empty flag/return true;
else return FALSE;
} int queuelength (Sqqueue q) {//* Returns the number of elements of Q, that is, the length of the queue */return (q.rear-q.front+max_qsize)%max_qsize;} Status GetHead (sqqueue q,qelemtype *e) {/* If the queue is not empty, return the team head element with E, and return OK; otherwise, return the error */if (q.front==q.rear)/* Queue null/back E
Rror;
*e=q.base[q.front];
return OK; } StatusEnQueue (Sqqueue *q,qelemtype e) {/* New team TAIL element * * Insert element e Q/if ((q->rear+1)%max_qsize==q->front)/* Queue full/return ERROR
;
q->base[q->rear]=e;
Q->rear= (q->rear+1)%max_qsize;
return OK; Status dequeue (sqqueue *q,qelemtype *e) {/* If the queue is not empty, delete Q's team head element, return its value with E, and return to OK; otherwise, return the error/if (q->front==q->rear)/* Team
Levin */return ERROR;
*e=q->base[q->front];
Q->front= (q->front+1)%max_qsize;
return OK;
} void Queuetraverse (Sqqueue q,void (*VI) (Qelemtype)) {/* calls function VI ()/int i for each element in queue Q from Team head to Team tail;
I=q.front;
while (i!=q.rear) {VI (q.base[i]);
I= (i+1)%max_qsize;
printf ("\ n"); }