- In circular queue whenever i call the enqueue function more than the size of the array. then i have used the condition that "queue is full". but it does not catch the condition and calls the function without any limit. why my limit is not working here is the code
#include<iostream>
#define N 5
using namespace std;
class CircularQueue
{
int front,rear,queue[N];
public:
CircularQueue()
{
front=rear=-1;
}
void enqueue(int x)
{
if(front == 0 && rear==(N-1)||rear == front-1)
{
cout<<"queue is full"<<endl;
}
else if(rear=front=-1)
{
rear=front=0;
queue[rear]=x;
}
else
{
rear=(rear 1)%N;
queue[rear]=x;
cout<<"the values which is inserted is "<<x<<endl;
}
}
};
int main()
{
CircularQueue Q1;
Q1.enqueue(7);
Q1.enqueue(9);
Q1.enqueue(8);
Q1.enqueue(-1);
Q1.enqueue(4);
Q1.enqueue(3);
Q1.enqueue(6);
return 0;
}
I have tried circular queue and than i call the enqueue function more than the size of array size by applying if else condition. it should have printed "queue is full" but it didn't. This queue take more values than the array size. why this happened
CodePudding user response:
Here is how to implement enqueue:
void enqueue(int x)
{
if ((front == 0 && rear == N -1) || (front == rear 1)) {
cout << "queue is full" << endl;
return;
}
if (front == -1) {
front = 0;
rear = 0;
}
else {
if (rear == N - 1)
rear = 0;
else
rear = rear 1;
}
queue[rear] = x;
cout << "the values which is inserted is " << x << endl;
}
CodePudding user response:
I suggest you have a data member count. the circular queue becomes very easy to handle.
if count == arr_size - 1 -> queue full
else
if count == 0 -> queue empty