#include <stdio.h> #include <stdlib.h> #include <string.h>
#define MAX_QUEUE_SIZE 10 typedef int elem_t; typedef struct _queue queue_t; struct _queue { elem_t data[MAX_QUEUE_SIZE]; int front,rear,size; };
int QueueIsFull(queue_t *q) { return ((q->rear+1)%MAX_QUEUE_SIZE == q->front); }
int QueueIsEmpty(queue_t *q) { return (q->rear == q->front); }
int InQueue(queue_t *q,elem_t d) { if (QueueIsFull(q)) { printf("Queue is full"); exit(1); } q->data[q->rear] = d; q->rear = (q->rear+1) % MAX_QUEUE_SIZE; q->size++;
return 0; }
elem_t OutQueue(queue_t *q) { elem_t retval;
if (QueueIsEmpty(q)) { printf("Queue is empty"); exit(1); } retval = q->data[q->front]; q->front = (q->front+1) % MAX_QUEUE_SIZE; q->size--;
return retval; }
elem_t ViewQueue(queue_t *q) { if (QueueIsEmpty(q)) { printf("Queue is empty"); return -1; } return q->data[q->front]; }
int InitQueue(queue_t *q) { memset(&q->data,0,MAX_QUEUE_SIZE * sizeof(elem_t)); q->rear = q->front = q->size =0; return 0; }
int TraverseQueue(queue_t *q) { int front,rear; printf("\n"); for( front = q->front,rear = q->rear ; front != rear ; front = (front+1)%MAX_QUEUE_SIZE) { printf("%d,",q->data[front]); }
return 0; }
int QueueFreeSize(queue_t *q) { return MAX_QUEUE_SIZE-1-q->size; }
int main(int argc,char *argv[]) { queue_t queue; elem_t retval;
int i;
InitQueue(&queue); printf("\nQueue size : %d",QueueFreeSize(&queue));
for (i=0;i<9;i++) InQueue(&queue,i*2);
printf("\nQueue size : %d",QueueFreeSize(&queue)); retval = OutQueue(&queue); retval = OutQueue(&queue); retval = OutQueue(&queue); printf("\nQueue size : %d",QueueFreeSize(&queue)); InQueue(&queue,55); InQueue(&queue,66); printf("\nQueue size : %d",QueueFreeSize(&queue));
TraverseQueue(&queue); return 0; }
|