I have read CLRS Introduction to Algorithms book, now I'm on Elementary data structure chapter. I read about queue concept and try to implement in c. I have tested a lot it work fine, but I have a little doubt on its working. Please tell me this implementation is correct or not.
#include <stdio.h>
#include <stdlib.h>
#define MAX 4
struct queue {
int array[MAX];
int head;
int tail;
};
void ENQUEUE(struct queue* p,int data) {
// error checking for overflow
if((p->tail == MAX-1 && p->head == 0 ) || (p->head == p->tail+1)) {
printf("\nQUEUE IS FULL!! ");
return;
}
p->array[p->tail] = data;
if(p->tail == MAX-1)
p->tail = 0;
else
p->tail = p->tail+1;
printf("\n%d data is added",data);
}
int DEQUEUE(struct queue* p) {
if(p->head == p->tail) {
printf("\nQUEUE IS EMPTY!!");
return -1;
}
int x = p->array[p->head];
if(p->head == MAX-1)
p->head = 0;
else
p->head = p->head+1;
printf("\n%d data is removed",x);
return x;
}
void SHOWQUEUE(struct queue* p) {
int i = 0;
i = p->head;
printf("p->head = %d & p->tail = %d",p->head,p->tail);
printf("\nQUEUE ELEMENTS:");
while(i != p->tail) {
printf("%d ",p->array[i]);
if(i == (MAX-1))
i = 0;
else
i = i+1;
}
}
int main() {
struct queue* Q;
Q = (struct queue*) malloc(sizeof (struct queue));
if(Q == NULL) {
printf("Memory allocation failed");
return -1;
}
Q->head = 1;
Q->tail = 1;
/* ENQUEUE(Q,1);
SHOWQUEUE(Q);
DEQUEUE(Q);
SHOWQUEUE(Q);
ENQUEUE(Q,1);
ENQUEUE(Q,1);
SHOWQUEUE(Q);
ENQUEUE(Q,1);
ENQUEUE(Q,1);
ENQUEUE(Q,1);
SHOWQUEUE(Q);
printf("head = %d & tail = %d ",Q->head,Q->tail);
*/
ENQUEUE(Q,98);
ENQUEUE(Q,20);
ENQUEUE(Q,16);
ENQUEUE(Q,2);
// ENQUEUE(Q,1);
// ENQUEUE(Q,2);
SHOWQUEUE(Q);
DEQUEUE(Q);
DEQUEUE(Q);
SHOWQUEUE(Q);
ENQUEUE(Q,5);
SHOWQUEUE(Q);
ENQUEUE(Q,3);
SHOWQUEUE(Q);
ENQUEUE(Q,10);
SHOWQUEUE(Q);
DEQUEUE(Q);
SHOWQUEUE(Q);
ENQUEUE(Q,12);
DEQUEUE(Q);
SHOWQUEUE(Q);
ENQUEUE(Q,2);
DEQUEUE(Q);
SHOWQUEUE(Q);
ENQUEUE(Q,1);
SHOWQUEUE(Q);
DEQUEUE(Q);
SHOWQUEUE(Q);
DEQUEUE(Q);
SHOWQUEUE(Q);
DEQUEUE(Q);
SHOWQUEUE(Q);
DEQUEUE(Q);
SHOWQUEUE(Q);
return 0;
}
but I have a little doubt on its working
what you mean by you doubt it's working ? Is it throwing exceptions ? Is one of the operation failing ? Normally broken code is off-topic for Code Review. \$\endgroup\$