Circular Queues Using Arrays (Data Structures in C)
#include<stdio.h>
#include<stdlib.h>
#define size 5
int f,r;
int CQ[size];
void cqinsert(int x)
{
if((r==size-1&&f==0)||(f==r+1))
{
printf("overflow. insertion not possible");
return;
}
if((f==-1)&&(r==-1))
{
f=0;
r=0;
}
else
{
if (r==size-1)
r=0;
else
r++;
}
CQ[r]=x;
}
int cqdelete()
{
int x;
if((f==-1)&&(r==-1))
{
printf("underflow exists.deletion not possible");
return(-1);
}
x=CQ[f];
if(f==r)
{
f=-1;
r=-1;
}
else if (f==size-1)
f=0;
else
f++;
return(x);
}
void cqtraverse()
{
int i;
if((f==-1)&&(r==-1))
{
printf("queue is empty");
return;
}
for(i=f; i!=r; (i=(i==size-1)?0:i+1) )
{
printf("%d\t",CQ[i]);
}
printf("%d \t",CQ[r]);
}
void main()
{
int x, choice;
f=-1;
r=-1;
while(1)
{
printf("menu 1:insert 2: delete 3:traversal 4: exit");
scanf("%d",&choice);
switch(choice)
{
case 1:printf("enter element to be inserted");
scanf("%d",&x);
cqinsert(x);
cqtraverse();
break;
case 2:x=cqdelete();
printf("deleted element is %d",x);
printf("remaining queue is");
cqtraverse();
break;
case 3:cqtraverse();
break;
default:exit(0);
}
}
}