--- title: キューの実装 author: kazu634 date: 2008-05-20 url: /2008/05/20/_998/ wordtwit_post_info: - 'O:8:"stdClass":13:{s:6:"manual";b:0;s:11:"tweet_times";i:1;s:5:"delay";i:0;s:7:"enabled";i:1;s:10:"separation";s:2:"60";s:7:"version";s:3:"3.7";s:14:"tweet_template";b:0;s:6:"status";i:2;s:6:"result";a:0:{}s:13:"tweet_counter";i:2;s:13:"tweet_log_ids";a:1:{i:0;i:4027;}s:9:"hash_tags";a:0:{}s:8:"accounts";a:1:{i:0;s:7:"kazu634";}}' categories: - C - Programming ---
#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(); }