I have written the following C++ code to implement a queue data structure. However, i have two problems:
Whenever i delete the front element, it works fine. However, when i press 2 to delete the front element even when the queue is empty, i get a message saying "Queue empty" followed by a 5 on the next line. How can i prevent the 5 from appearing and why is it coming?
When i completely fill the queue and want to display the contents, the queue is being printed infinitely without stopping. I think there is something wrong in the for loop in the display function. When the queue is not full, the display function works fine. How can i fix this?
My code:
#include<iostream>
using namespace std;
int data;
class queue {
private:
int front,rear,capacity,a[100];
public:
queue(int n)
{
rear=front=-1;
capacity=n;
}
void enqueue(int n)
{
if(front==-1)
{
front++;
rear=front;
a[front]=n;
return;
}
if(rear%capacity==(front-1)%capacity)
{
cout<<"Queue is full\n";
return;
}
rear=(rear+1)%capacity;
a[rear]=n;
}
int dequeue()
{
if(front==rear&&front==-1)
{
cout<<"Queue is empty";
return 0;
}
if(front==rear&&front!=-1)
{
data=a[front];
front=rear=-1;
return data;
}
data=a[front];
front=(front+1)%capacity;
return data;
}
void display()
{
int i;
for(i=front;i!=rear+1;i=(i+1)%capacity)
cout<<a[i]<<endl;
}
};
main()
{
int x,y,c;
cout<<"Enter capacity\n";
cin>>c;
queue q(c);
while(1)
{
cout<<"Select option 1.insert 2.delete 3.display 4.exit\n";
cin>>x;
switch(x)
{
case 1: cout<<"Enter the element\n";
cin>>y;
q.enqueue(y);
break;
case 2: q.dequeue();
break;
case 3: q.display();
break;
case 4: exit(0);
}
}
return 0;
}
Thanks!!