- Get link
- X
- Other Apps
Featured Post
Posted by
Unknown
on
- Get link
- X
- Other Apps
This is a simple implementation of Circular Queue using arrays.
A Circular Queue is a Data Structure in which the data is stored in a circular manner , i.e. the array can be reused from the front also.
A Circular Queue is a Data Structure in which the data is stored in a circular manner , i.e. the array can be reused from the front also.
#include <iostream>
#include <stdlib.h>
void err_quit(char* msg)
{
printf("%s\n",msg);
exit(0);
}
using namespace std;
class cirq{
int cirq_len;
int *queue;
public:
int front;
int rear;
cirq(int size);
~cirq();
void insert_rear(int item);
void delete_front();
void show();
};
cirq::cirq(int size = 0)
{
front = -1;
rear = -1;
cirq_len = size;
queue = new int[size];
}
cirq::~cirq()
{
delete[] queue;
}
void cirq::insert_rear(int item)
{
if((front == 0)&& (rear == cirq_len - 1) || (rear + 1 == front))
{
err_quit("Queue Overflow!!!");
}
if(rear == -1)
{
front = rear = 0;
}
else if(rear == (cirq_len - 1))
{
rear = 0;
}
else
rear++;
queue[rear] = item;
}
void cirq::delete_front()
{
if(front == -1 || rear == -1)
{
err_quit("Queue Underflow!!!");
}
front++;
}
void cirq::show()
{
int i;
if( front == -1 || rear == -1)
{
cout<<"Queue is empty!!!";
return;
}
if(front < rear)
for(i = front ; i <= rear; i++)
cout<<queue[i]<<" ";
else
{
for(i = front ; i <= (cirq_len - 1); i++)
cout<<queue[i]<<" ";
for(i = 0 ; i <= rear ; i++)
cout<<queue[i]<<" ";
}
cout<<endl;
}
int main()
{
int ch;
cirq c1(5);
c1.show();
c1.insert_rear(1);
c1.show();
c1.insert_rear(2);
c1.show();
c1.insert_rear(3);
c1.show();
c1.insert_rear(4);
c1.show();
c1.insert_rear(5);
c1.show();
c1.delete_front();
c1.show();
c1.delete_front();
c1.show();
c1.insert_rear(6);
c1.show();
c1.insert_rear(7);
c1.show();
c1.insert_rear(7);
c1.show();
c1.insert_rear(7);
c1.show();
}
Comments
is there any mistake in show function in (front<rear) , when there is only one data in the queue?
ReplyDelete