Sunday, October 2, 2011

Data Structure C program Circular Queue Dev c++

 #include <stdio.h>  
#define MAX 3
struct queue{
int x[MAX];
int front;
int rear;
}q;
void enqueue(int);
void display();
int dequeue();
int main()
{
q.front=-1;
q.rear=-1;
int ch,x,flag=1;
while(flag)
{
printf("1.Enqueue\n2.Dequeue\n3.Display\n4.Exit\n");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("Enter element:");
scanf("%d",&x);
enqueue(x);
break;
case 2:x=dequeue();
printf("Removed %d\n",x);
break;
case 3:display();
break;
case 4:flag=0;
break;
defalt:printf("Wrong choice\n");
}
}
}
void enqueue(int x)
{
if(q.front==(q.rear+1)%MAX)
printf("Queue full\n");
else if(q.rear==q.front)
{q.rear=q.front=-1;}
else
{
q.rear=(q.rear+1)%MAX;
q.x[q.rear]=x;
if(q.front==-1)
q.front=0;
}
}
int dequeue()
{
int x;
if(q.rear==-1 && q.front==-1)
printf("Queue Empty\n");
else if(q.rear==q.front)
{
x=q.x[q.front];
q.front=q.rear=-1;
return x;
}else
{
x=q.x[q.front];
q.front=q.front+1%MAX;
return x;
}
}
void display()
{
printf("%d %d Queue is\n",q.front,q.rear);
int i;
if(q.front<=q.rear)
{
for(i=q.front;i<=q.rear;i++)
printf("%d\n",q.x[i]);
}
else
{
for(i=q.front;i<=MAX-1;i++)
printf("%d\n",q.x[i]);
for(i=0;i<=q.rear;i++)
printf("%d\n",q.x[i]);
}
}

No comments:

Post a Comment