how to find number of elements in a Circular Queue

后端 未结 13 1440
我寻月下人不归
我寻月下人不归 2021-01-13 03:10

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

相关标签:
13条回答
  • 2021-01-13 03:51

    No of items in Circular queue is,

    size = (N-f+r) mod N
    

    where

    • N is the size of array used in circular fashion
    • f index of the front element
    • r index immediately past the rear element

    This formula work for both liner and circular queues.

    0 讨论(0)
  • 2021-01-13 03:51

    no. of elements = (rear + MAX_SIZE - front) % MAX_SIZE + 1

    0 讨论(0)
  • 2021-01-13 03:51

    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);
    }
    }
    
    0 讨论(0)
  • 2021-01-13 03:57

    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

    0 讨论(0)
  • 2021-01-13 03:58

    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
    
    0 讨论(0)
  • 2021-01-13 04:01

    if (Cqueue_front>Cqueue_rear) cout<<" The number of queue items are : "<

    0 讨论(0)
提交回复
热议问题