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
No of items in Circular queue is,
size = (N-f+r) mod N
where
This formula work for both liner and circular queues.
no. of elements = (rear + MAX_SIZE - front) % MAX_SIZE + 1
The easiest way to count the number of elements in the circular queue is:
if front > rear
(i.e. front is ahead than rear)
Just count the number of empty spaces in between
front - (rear+1)
else if front < rear
:
rear - front + 1
A C program if you need to:
int find_ele(int total,int front,int rear){
if(rear < front ) { \\1st case
int res = front - rear + 1;
return (total-res);}
else{
return (rear - front + 1);
}
}
can your queue contain the same element in more than one location? if it can then I don't think you can do this as there is no way to know the difference between:
a->b->c
and
a->b->c->a->b->c
if it can't contain the same element more than once, just look through the queue until you find an element you have already seen
actually the size would be,
size = front > rear ? (MAX - front + rear + 1) : (rear - front + 1);
or one can go for a generic formula:
size = abs(abs(MAX - front) - abs(MAX -rear));//this works in every situation
if (Cqueue_front>Cqueue_rear) cout<<" The number of queue items are : "<