Create a new variable size inside the struct QUEUE, which is initialized to 0 when the queue is created and refers to the amount of data stored in you queue.
typedef struct QUEUE {
int head, tail,size;
int list[4];
} queue;
void create( queue *q ) {
q->head = 0;
q->tail = -1;
q->size=0;
}
Hence size 0 would mean no data is present in our queue and size 4 will mean the queue is full.
int empty( queue *q ) {
if ( q->size==0 )
return 1;
else
return 0;
}
int full( queue *q ) {
if ( q->size==4)
return 1;
else
return 0;
}
When you enqueue a data, size is increased by 1 and when you dequeue a data, size is decreased by 1.
void enqueue( queue *q ) {
int i, data;
if ( full( q ) == 1 )
printf( "\nQueue is Full" );
else {
printf( "\nEnqueue Integer : " );
scanf( "%d", &data );
q->tail++;
q->size++;
if(q->tail==4){
q->tail=0;
}
q->list[q->tail] = data;
if(tail==4){
q->tail==0;
}
}
}
void dequeue( queue *q ) {
int i;
if ( empty( q ) == 1 )
printf( "\n Queue is Empty" );
else{
q->head++;
q->size--;
}
}
NOTE-Your code lacked the circular flow of queue. When tail has crossed the last block of memory allocated, it should get to the first block.
So, we added this inside the enqueue function:
if(tail==4){
q->tail==0;
}