C++ program for Circular Queue
Circular queue
In a normal Queue Data Structure, we can insert elements until queue becomes full. But once queue becomes full, we can not insert the next element until all the elements are deleted from the queue.
Circular Queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle.
Program:
#include<iostream>
#include<stdlib.h>
using namespace std;
int siz,front=0,rear=0;
void insert(int q[],int n)
{
if(front==1&&rear==siz||front==rear+1)
{cout<<"Overflow ";
exit(0);}
else if (rear==0)
front=rear=1;
else if(rear==siz)
rear=1;
else rear++;
q[rear]=n;
}
void del(int q[])
{int rak;
if(front==0)
{cout<<"Underflow ";exit(0);}
rak=q[front];
if(front==rear)
front=rear=0;
else if (front==siz)
front=1;
else front++;
cout<<"\nDeleted element is "<<del;
}
void display(int q[])
{
for(int r=front;r<rear;r++)
cout<<q[r]<<"<-";
cout<<q[rear];
}
main()
{
int raks,c;
char ch;
cout<<"Enter size of queue ";
cin>>siz;
int q[siz];
do
{
cout<<"Enter data to create a queue ";
cin>>raks;
insert(q,raks);
cout<<"The queue is ";
display(q);
cout<<"\nWant to insert more elements ";
cin>>ch;
}while(ch=='y'||ch=='Y');
cout<<"Enter choice \n1.Insertion \n2.Deletion ";
cin>>c;
switch(c)
{
case 1:do
{
cout<<"Enter data to insert ";
cin>>raks;
insert(q,raks);
cout<<"\nThe queue is ";
display(q);
cout<<"\nWant to insert more elements ";
cin>>ch;
}while(ch=='y'||ch=='Y');
break;
case 2:
cout<<"\n-----Deletion-----";
do{
del(q);
cout<<"\nThe queue is ";
display(q);
cout<<"\nWant to delete more ";
cin>>ch;
}while(ch=='y'||ch=='Y');
break;
default:cout<<"\nWrong choice ";
}
cout<<"\nThe queue is ";
display(q);
}

Comments
Post a Comment