Circular queue Display

Viewed 134

In

void Queue::displayQueue() 
{ 
if (front == -1) 
{ 
    printf("\nQueue is Empty"); 
    return; 
} 
printf("\nElements in Circular Queue are: "); 
if (rear >= front) 
{ 
    for (int i = front; i <= rear; i++) 
        printf("%d ",arr[i]); 
} 
else // Why do I need two loops in this else?
{ 
    for (int i = front; i < size; i++) 
        printf("%d ", arr[i]); 

    for (int i = 0; i <= rear; i++) 
        printf("%d ", arr[i]); 
} 

Why can't I just print i from front to rear, instead of splitting it into two lines?

1 Answers

The implementation you've discussed about...in that queue elements can be in two manner:

  1. linear manner like [4, 3, 1, 2, <empty_pos>, <empty_pos>, <empty_pos>] or
  2. circular manner like [1, 2, <empty_pos>, <empty_pos>, <empty_pos>, 4, 3]

In the latter case, 4 is the front of the queue and 2 is the last element of queue. So, you may got why index of front is greater than index of rear...

Also, you can just do things with a single loop, if you code like below:

// no need to check with if/else, remove the if/else part and
// just do the following
for (int i = front; i != rear; i = ((i + 1) % size)) {
  printf("%d ",arr[i]); // print elem
}
if(size > 0) printf("%d ",arr[i]); // don't forget it, it prints the rear elem
Related