『新版 C言語によるアルゴリズムとデータ構造』から。
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int max; /* the size of the queue */
int num; /* Current Number of the elements */
int front; /* the front cursor */
int rear; /* the rear cursor */
int *que; /* the pointer to the first element */
} Queue;
/* initialization of the que */
int QueueAlloc(Queue *q, int max)
{
q->num = q->front = q->rear = ;
if ((q->que = calloc(max, sizeof(int))) == NULL) {
q->max = ;
return(-1);
}
q->max = max;
return();
}
/* Clear the queue */
void QueueFree(Queue *q)
{
if (q->que != NULL) {
free(q->que);
q->max = q->num = q->front = q->rear = ;
}
}
/* Enque the data into the queue */
int QueueEnque(Queue *q, int x)
{
if (q->num >= q->max) return(-1);
else {
q->num++;
q->que[q->rear++] = x;
if (q->rear == q->max) q->rear = ;
return();
}
}
/* Deque the data from the queue */
int QueueDeque(Queue *q, int *x)
{
if (q->num <= ) return(-1);
else {
q->num--;
*x = q->que[q->front++];
if (q->front == q->max) q->front = ;
return();
}
}
/* the size of the que */
int QueueSize(const Queue *q)
{
return(q->max);
}
/* the number of the data stored in the queue */
int QueueNo(const Queue *q)
{
return(q->num);
}
/* Is the queue empty? */
int QueueIsEmpty(const Queue *q)
{
return(q->num <= );
}
/* Is the queue full? */
int QueueIsFull(const Queue *q)
{
return(q->num >= q->max);
}
int main(void)
{
Queue que;
if (QueueAlloc(&que, 100) == -1) {
puts("Fail to secure the memory of the queue.");
return(1);
}
while (1) {
int m, x;
printf ("Current Number of the Data: %d / %d\n", QueueNo(&que), QueueSize(&que));
printf ("(1) Enque (2) Deque 0) Exit");
scanf("%d", &m);
if (m == ) break;
switch (m) {
case 1:
printf ("Data: ");
scanf("%d", &x);
if (QueueEnque(&que, x) == -1) puts("Fail to enque the data into the que");
break;
case 2:
if (QueueDeque(&que, &x) == -1) puts("Cannot Deque!");
else printf ("The Decued Data: %d\n", x);
break;
}
}
QueueFree(&que);
return();
}