Thursday, January 3, 2013

Implementing Circular Queue in C


Not full working code, but you get the idea
elements are inserted clockwise, deleted clockwise.

Basic conditions :
If rear is one position to the left of front --> queue is empty
If rear is two positions to the left of front --> queue is full

So the array of size n holds only n-1 elements at a time, so as to differentiate queue-empty and queue-full scenarios.

---------------------------------------------------------------------------------------------

front = 0;
rear = n - 1;
int A[n];

void enqueue(int elem){
if((rear+front+2)%n == 0){
printf("Queue is full");
return;
}
rear = (rear+1)%n;
A[rear] = elem;
}

int dequeue(){
if((front-rear+n)%n == 1){
printf("Queue is empty");
return;
}
int temp = A[front];
front = (front+1)%n;
return temp;
}

No comments:

Post a Comment