Circular Queue Example C

#include<stdio.h>
#include<process.h>
#include<stdlib.h>
#include<math.h>
#define MAX 3
typedef int itemtype;
typedef struct queue* qptr;
struct queue
{
itemtype data[MAX];
int front,rear;
};
void init(qptr q);
void add(qptr q,itemtype x);
void removeq(qptr q);
int full(qptr q);
int empty(qptr q);
int count(qptr q);

void init(qptr q)
{
q->front=0;
q->rear=-1;
}

void add(qptr q,itemtype x)
{
if(!full(q))
{
q->rear=(q->rear+1)%MAX;
q->data[q->rear]=x;
}
else
{
printf("\nqueue is full...\n");
}
}

void removeq(qptr q)
{
if(!empty(q))
{
	printf("\n%d removed \n",q->data[q->front]);
	q->data[q->front]=-1;
	printf("\n%d after remove \n",q->data[q->front]);
	q->front=(q->front+1)%MAX;
}
else
{
printf("\nqueue is empty\n");
}
}

int full(qptr q)
{
if(count(q)==MAX)
return 1;
else
return 0;
}

int empty(qptr q)
{
return (!count(q));
}

int count(qptr q)
{
	if((q->front>q->rear)&&((q->data[q->rear]!=-1)&&(q->rear!=-1)))
		return (MAX-((q->front-q->rear)-1));
	else if((q->front<=q->rear)&&(q->data[q->rear]!=-1))
		return abs(((q->front-q->rear)-1));
	else
		return 0;
}



int main()
{
qptr q;
int ch,x;
char choice;
q=(qptr)malloc(sizeof(struct queue));
init(q);
do
{
printf("\n || MENU || \n");
printf("\n 1. add in cqueue");                 
printf("\n 2. remove from cqueue");
printf("\n 3. count"); 
printf("\n\n Enter your choice (1-3) : ");
scanf("%d",&ch);
if(ch==1)
{
printf("\n Enter value in queue : ");
scanf("%d",&x);
add(q,x);
}
else if(ch==2)
{
removeq(q);
}
else if(ch==3)
{
printf("\n count = %d \n",count(q));
}
else
{
printf("\n Invalid choice...\n");
}
	fflush(stdin);
	printf("\n want to continue (y/n) : ");
	scanf("%c",&choice);
}while(choice=='y'||choice=='Y');
system("pause");
}


Leave a Reply