I made a function to check if my circular queue is full, but it always return 1 (aka "true");
this is my Queue setup:
#define MAX_LENGTH 150
typedef double ElementType;
typedef int bool;
typedef struct
{
ElementType Elements[MAX_LENGTH];
int front;
int rear;
} Queue;
and this is my function:
int isFull(Queue Q)
{
if (Q.front == Q.rear )
return 1;
if ((Q.rear == MAX_LENGTH) && (Q.front == 0))
return 1;
return 0;
}
This function always return 1 mean the queue is full even though i have not put anything in the queue yet.
how do I fix this? Thanks.
Edit:
I edited Q.rear
to Q.rear 1
Here is how I initialize the Queue.
void resetQueue(Queue *Q)
{
Q->front = -1;
Q->rear = -1;
};
I found out that the problem is right at:
if (Q.front == Q.rear 1)
return 1;
part.
Now I just can put 2 Elements in the queue, if I put the third Elements, it will become full.
CodePudding user response:
As part of your problem, please learn the difference between prefix
and postfix
(i.e. between Q.rear
and Q.rear
).
Since you initialize both front
and rear
to the same value, the comparison Q.front == Q.rear
will be true, because the increment happens after the value of Q.rear
is used.
The code
if (Q.front == Q.rear )
{
// ...
}
is really more equivalent to
int old_value_of_rear = Q.rear;
Q.rear = Q.rear 1;
if (Q.front == old_value_of_rear)
{
// ...
}
If you want to compare Q.front
with Q.rear 1
, use that exact addition:
if (Q.front == Q.rear 1)