Question

Possible Duplicate:
how to find number of elements in a Circular Queue

I am implementing a circular queue but I can't get the queue's size correctly. I found a previous topic concerning the same problem and the solution proposed was to use two pointers and to increment the second one while it does not point to the same object as the first one. But I think this appoach can only work when there are different objects in the queue. In my case, all the object are similar. how can I get the size of the circular queue? This formula doesn't work for me too:

int size = abs(m_front -m_tail) ; 

Where m_front and m_tail are the tail and front queue indexes.

Thanks

Was it helpful?

Solution

This should do it:

if m_front > m_tail 
    size = (m_front - m_tail)
else
    size = (m_front + N - m_tail)

Where N is the length of your array.

Alternatively, you can just keep track of it yourself by incrementing a counter when you Queue(), and decrementing it when you Dequeue().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top