how do i find the number of items in a circular queue?
|front - rear| doesnt always work.
is there one equation to know how many element is in a cir
The standard answer is to take two iterators at the beginning, increment the first one once, and the second one twice. Check to see if they point to the same object. Then repeat until the one that is incrementing twice either hits the first one or reaches the end. inside this loop use the counter to get the length of the CQuueeue
int lenghtQueue(queue* q){
int len =0 ;
if (isEmpty(q))
return 0 ;
queue* qe = q->next ;
len ++ ;
while(qe!=q){
len ++ ;
qe=qe->next ;
}
return len ;
}
What do you need to implement a circular queue ?
Answer: you will need front and rear nodes + list of items + count_items.
Of course it is only implemented like this when the queue is finite, when talking about
dynamic allocation it will be different.
Take a look at an example in C Language,
typedef struct
{
TYPE items[MAXSIZE];
TYPE front;
TYPE rear;
int count_items;
} QUEUE;
This will assure you the exact amount of items are currently exist in the queue.
When you want to insert an item to the queue, you will simply increment rear and count_items, and when you want to remove an item from the queue, you will simply decrement rear and count_items.
None of the formulas take into account the empty (zero) case. This will give you the number of free bytes available in the queue:
FreeSpace = (printRdQue == printWrQue) ? PRINT_QUEUE_SIZE :
(PRINT_QUEUE_SIZE - printWrQue + printRdQue) % PRINT_QUEUE_SIZE;
Assuming you implement it using an array with size N
so there are pointers pointing to the front and rear. Use the following formula:
size = front > rear ? (front - rear) : (front+N - rear);
Assuming you are using array of size N for queue implementation, then size of queue would be
size = (N-front + rear) mod N
.