#ifndef QUEUE_H_#define QUEUE_H_#include<stdbool.h>#define MAXQSIZE 6#define OK 1#define ERROR 0#define OVERFLOW -1typedefint Item;typedefstruct{
Item *base;int front;int rear;}Queue;/*initialize the queue*/voidInitQueue(Queue *q);/*return the length of the queue*/unsignedintQueueLength(Queue q);/*Destroy the queue*/voidDestroyQueue(Queue *q);/*determine if the queue is empty*/
bool IsEmpty(Queue q);/*determine if the queue is full*/
bool IsFull(Queue q);/*return the head elem of the queue*/
Item Top(Queue q);/*return the back elem of the queue*/
Item Back(Queue q);/*enqueue, insert the rear*/
bool EnQueue(Queue *q, Item e);/*dequeue, pop the front*/
bool DeQueue(Queue *q);/*print the queue*/voidPrintQueue(Queue q);#endif
queue.c
#include"queue.h"#include<stdio.h>#include<stdlib.h>voidInitQueue(Queue *q){
q->base =(Item*)malloc(MAXQSIZE *sizeof(Item));if(q->base ==NULL)exit(OVERFLOW);
q->front =0;
q->rear =0;}/*return the length of the queue*/unsignedintQueueLength(Queue q){return(q.rear - q.front + MAXQSIZE)% MAXQSIZE;}/*Destroy the queue*/voidDestroyQueue(Queue *q){
q->base =NULL;
q->rear =0;
q->front =0;free(q->base);}/*determine if the queue is empty*/
bool IsEmpty(Queue q){return q.rear == q.front;}
bool IsFull(Queue q){return(q.rear +1)% MAXQSIZE == q.front;}/*return the head elem of the queue*/
Item Top(Queue q){return q.base[q.front];}/*return the back elem of the queue*/
Item Back(Queue q){return q.base[(q.rear -1+ MAXQSIZE)% MAXQSIZE];}/*enqueue, insert the rear*/
bool EnQueue(Queue *q, Item e){if(IsFull(*q))return ERROR;
q->base[q->rear]= e;
q->rear =(q->rear +1)% MAXQSIZE;return OK;}/*dequeue, pop the front*/
bool DeQueue(Queue *q){if(IsEmpty(*q))return ERROR;
q->front =(q->front +1)% MAXQSIZE;return OK;}/*print the queue*/voidPrintQueue(Queue q){int i, j;for(i =0, j = q.front; i <QueueLength(q); i++, j =(j +1)% MAXQSIZE){printf("%d\n",q.base[j]);}}
main.c
#include"queue.h"#include<stdio.h>int main (){
Queue q;InitQueue(&q);EnQueue(&q,1);EnQueue(&q,2);EnQueue(&q,3);EnQueue(&q,4);EnQueue(&q,5);if(IsFull(q))printf("hihi\n");DeQueue(&q);printf("%d\n%d\n", q.front, q.rear);EnQueue(&q,6);printf("%d\n",Top(q));//printf("%d\n", q.base[0]);printf("%d\n",Back(q));PrintQueue(q);DestroyQueue(&q);}