how to find number of elements in a Circular Queue

john picture john · Dec 16, 2010 · Viewed 32k times · Source

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 circular queue?

Answer

Nikhil Doomra picture Nikhil Doomra · Nov 6, 2011

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