I’m trying to implement a queue using an array. Here is my code:
#include <iostream.h>
#define SIZE 5
class queue
{
int *Queue, front, rear;
public:
queue() {
Queue = new int[SIZE];
front = rear = -1;
}
void push() {
if (rear == (SIZE-1)) {
cout<<"\n Overflow!";
} else {
rear++;
cout<<"\n Enter element: ";
cin>>Queue[rear];
}
}
void pop() {
if (front == rear) {
cout<<"\n Underflow!";
} else {
cout<<"\nElement popped: "<<Queue[++front];
}
}
void display() {
if (front == rear) {
cout<<"\n Queue Empty";
} else {
for(int i = (front+1); i<=rear; i++) {
cout<<Queue[i]<<" ";
}
}
}
};
int main()
{
int choice;
queue q;
while(choice != 4)
{
cout<<"\n\n Enter your choice :"
<<"\n 1. Push an element into Queue."
<<"\n 2. Pop an element from Queue."
<<"\n 3. Display the Queue."
<<"\n 4. Exit the program.\n\n";
cin>>choice;
switch (choice) {
case 1:
q.push();
break;
case 2:
q.pop();
break;
case 3:
q.display();
break;
case 4:
break;
}
}
return 0;
}
The thing is that once the overflow is met, even after popping an element the rear remains the same and another element is not added when there is a vacant space where it can go.
The solution for this could be to shift every element one place ahead so that there is empty spot at the end but I am having trouble with the shift. Also, if I try inserting after popping 2-3 times before reaching overflow then it still gives overflow even when there are only 3 elements in the queue.
How can I solve this?
You never reset
frontorrear, they keep increasing forever.the overlflow test is also wrong:
what you should be testing is if your are about to overwrite front. I think you will benefit from keeping just
frontand the number of elementsNinstead. Then overflow and underflow becomesN>SIZEandN==0instead. Then just increase and decreaseNas you pop and push. Keep front as it is but also keep it moduloSIZE.Also, as written in a comment. No need to move around the data.