I happen to come across the implementation of an array based queue while reading through the internet:
#include <stdio.h>
#include <stdlib.h>
typedef int item_t;
typedef struct {item_t *base;
int front;
int rear;
int size;} queue_t;
queue_t *create_queue(int size)
{ queue_t *qu;
qu = (queue_t *) malloc( sizeof(queue_t) );
qu->base = (item_t *) malloc( size * sizeof(item_t) );
//printf("q->base address %p\n",qu->base);
qu->size = size;
qu->front = qu->rear = 0;
return( qu );
}
int enqueue( item_t x, queue_t *qu)
{
printf("modulo result %d\n",((qu->rear +2)% qu->size));
if ( qu->front != ((qu->rear +2)% qu->size) )
{ qu->base[qu->rear] = x;
qu->rear = ((qu->rear+1)%qu->size);
return( 0 );
}
else
return( -1 );
}
Here is the create queue and enqueue logic from the code. Initially front and rear is zero.qu->front and ((qu->rear +2)% qu->size) is not equal so the item will be enqueued. I am unable to understand why is 2 used in this logic- ((qu->rear +2)% qu->size) ?