Circular Queue

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

CIRCULAR QUEUE

#include<iostream>
#include<conio.h>
using namespace std;

struct node
{
int data;
node* next;//link
};
//made global pointer varaibles of "node" and assgined "NULL"
node* front=NULL;
node* rear=NULL;

class cQueue//Made the class to implement all the functions of queue


{
private:
node* cur;//current is used as a iterator for like
"traversing" etc.
node* temp;//for creating a new item or node

public:
cQueue()//constructor
{
cur=NULL;
temp=NULL;
}

void enQueue(int n)
{
temp=new node;
temp->data=n;
if(front==NULL)//empty
{
temp->next=temp;
rear=temp;
front=rear;
}
else
{
rear->next=temp;
temp->next=front;//as queue is circular so
last node points to the first
rear=temp;
}
}

void deQueue()
{
if(front==NULL)
{
cout<<"Queue is empty!\n";
}

/*when queue has only one item both rear and front
will be pointing that same item so for that we
have to perform the following*/
if(front==rear)
{
delete(front);
front=NULL;
rear=NULL;
}

//when the queue contain more than one items


else
{
cur=front;
front=front->next;

/*as the queue is circular so when we will del


a node the last node has to point to the node
that has come to the front of the queue*/
rear->next=front;

delete(cur);
}
}

void cFront()
{
if(front==NULL)
{
cout<<"Queue is empty!\n";
}
else
{
cout<<front->data<<endl;
}
}
void isEmpty()
{
if(front==NULL)
{
cout<<"Queue is empty!\n";
}
else
{
cout<<"Queue is not empty\n";
}
}

void disp()
{
if(front==NULL)
{
cout<<"Queue is Empty!\n";
}
else
{
cur=front;
while(cur->next!=front)
{
cout<<cur->data<<"\t";
cur=cur->next;
}
cout<<cur->data<<"\t";
cout<<"\n";
}
}
};

main()
{
cQueue obj;
obj.enQueue(4);
obj.enQueue(5);
obj.enQueue(6);

obj.disp();

obj.deQueue();

obj.disp();
}

You might also like