Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find number of elements in a Circular Queue

How do I find the number of items in a circular queue? |front - rear| doesn't always work.

Is there one formula to know how many elements are there in a circular queue using front, rear and size of the array?

like image 415
john Avatar asked Dec 16 '10 09:12

john


People also ask

How many pointers are used in circular queue?

two pointers FRONT and REAR.

How do you print elements in a circular queue?

we need to add... System. out. print(" "+arr[rear]); ... after while loop end.

What is circular queue example?

CPU Scheduling: The operating system also uses the circular queue to insert the processes and then execute them. Traffic system: In a computer-control traffic system, traffic light is one of the best examples of the circular queue. Each light of traffic light gets ON one by one after every jinterval of time.


2 Answers

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
like image 149
Nikhil Doomra Avatar answered Nov 08 '22 23:11

Nikhil Doomra


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);
like image 29
unsym Avatar answered Nov 08 '22 23:11

unsym