0

So I have to implement a circular queue using array and I've used the following code to do so. However, for some reason when I try to add the 5th element to my queue, it does not seem to work. ALso, it doesnt work when I try to dequeue after adding 4 elements in my queue.

typedef struct {
    int array[5],front,rear;
} cqueue;

void init(cqueue *q)
{
    q->front=q->rear=-1;
}

int enqueue(cqueue *q,int val){
    if(q->front==(((q->rear)+1)%5)){
        printf("Overflow");
        return 1;
    }
    else{
        q->front = (q->front==-1) ? 0:q->front;
        q->rear=(q->rear+1)%5;
        q->array[q->rear]=5;
        return 0;
    }
}

int dequeue(cqueue *q,int *d){
    if(q->front==q->rear){
        if(q->front==-1){
            printf("Underflow");
            return 1;
        }
        else{
            *d=q->array[q->front];
            q->rear=q->front=-1;
            return *d;
        }
    }
    else{
        *d=q->array[q->front];
        q->front=((q->front)+1)%5;
        return *d;
    }
}     

void display(cqueue *q){
    int n=q->front;
    do{
        printf("%d\n",q->array[n]);
        n=(n+1)%5;
    } while(n!=(q->rear+1)%5);
}

int main() {
        
    int i;
    cqueue *q1;
    init(q1);
    enqueue(q1,10);
    enqueue(q1,10);
    enqueue(q1,10);
    enqueue(q1,10);
    enqueue(q1,10);



    // dequeue(q1,&i);
    // dequeue(q1,&i);
    // enqueue(q1,10);
    display(q1);


        
    return 0;
    }

I don't know what to try or where I went wrong. Can anyone help?

0 Answers0