In this tutorial we learn how to create circular queue in cpp. In the data structure queue is one type of data storage type.We include the data in queue. The queue working first in first out(FIFO).It is a linear data structure.In this we can insert element until queue become full.
following is the simple coding for circular queue:-
#include<iostream.h>
#include<conio.h>
#define SIZE 5
class cqueue
{
int front,rear;
int cq[SIZE];
public:
cqueue()
{
front=rear=-1;
}
void insert(int ele)
{
if(rear==front-1||front==0&&rear==SIZE-1)
{
cout<<"Circular queue is full";
return;
}
else if(front==-1 &&rear==-1)
{
front=rear=0;
cq[rear]=ele;
}
else
{
rear=(rear+1)%SIZE;
cq[rear]=ele;
}
}
int deleted()
{
int x;
if(front==-1&& rear==-1)
{
cout<<"\nCircular queue is empty";
return 0;
}
else
{
if(front==rear)
{
x=cq[rear];
front=rear=-1;
return x;
}
else
{
x=cq[front];
front=(front+1)%SIZE;
return x;
}
}
}
void display()
{
if(front==-1 && rear==-1)
{
cout<<"\nCircular queue is empty";
return;
}
else
{
if(front<=rear)
{
for(int i=front;i<=rear;i++)
{
cout<<" "<<cq[i];
}
}
else
{
for(int i=front;i<SIZE;i++)
{
cout<<" "<<cq[i];
}
if(front>rear)
{
for(int i=0;i<=rear;i++)
{
cout<<" "<<cq[i];
}
}
}
}
}
};
void main()
{
cqueue c;
int ch,ele,m;
clrscr();
do
{
cout<<"\nMenu\n1.Insert\n2.Delete\n3.Display\n4.Exit";
cout<<"\nEnter your choice:";
cin>>ch;
switch(ch)
{
case 1:
cout<<"\nEnter element:";
cin>>ele;
c.insert(ele);
break;
case 2:
m=c.deleted();
cout<<"\nDleted element:"<<m;
break;
case 3:
c.display();
break;
case 4:
cout<<"\nExit";
break;
}
}while(ch!=4);
getch();
}
The above program shows the following output:
following is the simple coding for circular queue:-
#include<iostream.h>
#include<conio.h>
#define SIZE 5
class cqueue
{
int front,rear;
int cq[SIZE];
public:
cqueue()
{
front=rear=-1;
}
void insert(int ele)
{
if(rear==front-1||front==0&&rear==SIZE-1)
{
cout<<"Circular queue is full";
return;
}
else if(front==-1 &&rear==-1)
{
front=rear=0;
cq[rear]=ele;
}
else
{
rear=(rear+1)%SIZE;
cq[rear]=ele;
}
}
int deleted()
{
int x;
if(front==-1&& rear==-1)
{
cout<<"\nCircular queue is empty";
return 0;
}
else
{
if(front==rear)
{
x=cq[rear];
front=rear=-1;
return x;
}
else
{
x=cq[front];
front=(front+1)%SIZE;
return x;
}
}
}
void display()
{
if(front==-1 && rear==-1)
{
cout<<"\nCircular queue is empty";
return;
}
else
{
if(front<=rear)
{
for(int i=front;i<=rear;i++)
{
cout<<" "<<cq[i];
}
}
else
{
for(int i=front;i<SIZE;i++)
{
cout<<" "<<cq[i];
}
if(front>rear)
{
for(int i=0;i<=rear;i++)
{
cout<<" "<<cq[i];
}
}
}
}
}
};
void main()
{
cqueue c;
int ch,ele,m;
clrscr();
do
{
cout<<"\nMenu\n1.Insert\n2.Delete\n3.Display\n4.Exit";
cout<<"\nEnter your choice:";
cin>>ch;
switch(ch)
{
case 1:
cout<<"\nEnter element:";
cin>>ele;
c.insert(ele);
break;
case 2:
m=c.deleted();
cout<<"\nDleted element:"<<m;
break;
case 3:
c.display();
break;
case 4:
cout<<"\nExit";
break;
}
}while(ch!=4);
getch();
}
The above program shows the following output:
No comments:
Post a Comment