Reputation: 11
I'm having issue with checking if my circular queue is full or not. The maximum size for the queue is set to 5. However, after putting in 4 elements, it doesn't let me add a fifth element. I'm stuck.
void init (struct data* ptr) {
ptr->rear = 0;
ptr->front = 0;
}
void display (struct data* ptr) {
if (empty(ptr)) {
printf("\nNo data to display. The queue is EMPTY.\n");
} else if (ptr->rear > ptr->front) {
for (int i = ptr->front; i < ptr->rear; i++) {
printf ("%d ", ptr->data[i]);
}
} else {
for (int i = 0; i < ptr->rear; i++) {
printf("%d ", ptr->data[i]);
}
for (int i = ptr->front; i < MAX; i++) {
printf("%d ", ptr->data[i]);
}
}
printf("\n");
}
bool empty (struct data* ptr) {
if (ptr->rear == ptr->front) {
return true;
} else {
return false;
}
}
void enQueue (struct data* ptr, int input) {
int nR = (ptr->rear + 1) % MAX;
if (nR == ptr->front) {
printf("\nQueue is FULL.\n\n");
} else {
ptr->data[ptr->rear] = input;
ptr->rear = nR;
printf("\nElement %d is inserted.\n\n", input);
}
}
Upvotes: 0
Views: 752
Reputation: 13171
Your queue has five elements, and rear can point to any of them. So front also can point to any of the five elements, and thus indicate five states. But if you want the queue to contain 0,1,2,3,4 or 5 items, that's six different states to distinguish. You're trying to put 6 pigeons into 5 pigeonholes.
To make a circular queue work, you have three choices: (1) add an "empty" or "full" flag to distinguish between those two states; (2) add a "fill count" which can also be used for that purpose; or (3) resign yourself to never putting more than N-1 items in your N-size queue.
Upvotes: 4