how to find number of elements in a Circular Queue

后端 未结 13 1438
我寻月下人不归
我寻月下人不归 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:39

    The standard answer is to take two iterators at the beginning, increment the first one once, and the second one twice. Check to see if they point to the same object. Then repeat until the one that is incrementing twice either hits the first one or reaches the end. inside this loop use the counter to get the length of the CQuueeue

    0 讨论(0)
  • 2021-01-13 03:40
    int lenghtQueue(queue* q){
    
         int len =0 ;
         if (isEmpty(q))
                return 0 ;
    
          queue* qe = q->next ;
          len ++ ;
    
           while(qe!=q){
                 len ++ ;
                 qe=qe->next ;           
           }
               return len ;
      }
    
    0 讨论(0)
  • 2021-01-13 03:43

    What do you need to implement a circular queue ?

    Answer: you will need front and rear nodes + list of items + count_items.

    Of course it is only implemented like this when the queue is finite, when talking about

    dynamic allocation it will be different.

    Take a look at an example in C Language,

    typedef struct
    {
    
    TYPE items[MAXSIZE];
    
    TYPE front;
    
    TYPE rear;
    
    int count_items;
    
    } QUEUE;
    

    This will assure you the exact amount of items are currently exist in the queue.

    When you want to insert an item to the queue, you will simply increment rear and count_items, and when you want to remove an item from the queue, you will simply decrement rear and count_items.

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

    None of the formulas take into account the empty (zero) case. This will give you the number of free bytes available in the queue:

    FreeSpace = (printRdQue == printWrQue) ? PRINT_QUEUE_SIZE :
               (PRINT_QUEUE_SIZE - printWrQue + printRdQue) % PRINT_QUEUE_SIZE;
    
    0 讨论(0)
  • 2021-01-13 03:49

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

    Assuming you are using array of size N for queue implementation, then size of queue would be size = (N-front + rear) mod N.

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