Implementation Circular Queue using ARRAY

amannarayanm · updated October 20, 2021 · C
#include <stdio.h>
#include <stdlib.h>

struct Queue{
  int size;    
  int f;
  int r;
  int *arr;
};

void traversal(struct Queue *q){
    for(int i=q->f+1;i<= q->r ;i++){
        printf(" %d",q->arr[i]);
    }
    printf("\n");
}

int isEmpty(struct Queue *q){
    if(q->f == q->r){
        return 1;
    }
    return 0;
}

int isFull(struct Queue *q){
    if((q->r +1)%q->size == q->f){
        return 1;
    }
    return 0;
}

void Enqueue(struct Queue *q,int data){
    if(isFull(q)){
        printf("\nQueue OverFlow!");
    }
    else{
        printf("\nEnqueue element: %d",data);
        q->r = (q->r+1)%q->size;
        q->arr[q->r] = data;
    }
}

int Dequeue(struct Queue *q){
    if(isEmpty(q)){
        printf("\nQueue UnderFlow!");
    }
    else{
        q->f = (q->f+1)%q->size;
        int element = q->arr[q->f];
        return element;
    }
    return -1;
}

int main() {
    
    
    struct Queue *q = (struct Queue*)malloc(sizeof(struct Queue));
    q->size = 5;
    q->f == 0;
    q->r == 0;
    q->arr = (int *)malloc(q->size*sizeof(int));
    
    Enqueue(q,98);
    Enqueue(q,83);
    Enqueue(q,35);
    Enqueue(q,65);
    
    printf("\n|||||||||||||||||||||||||||||||||||");
    printf("\nValue of Front: %d\nValue of Rear : %d",q->f,q->r);
    printf("\n|||||||||||||||||||||||||||||||||||");
    
    printf("\nDequeue element : %d",Dequeue(q));
    printf("\nDequeue element : %d",Dequeue(q));
    printf("\nDequeue element : %d",Dequeue(q));  
    printf("\nDequeue element : %d",Dequeue(q)); 
    
    printf("\n|||||||||||||||||||||||||||||||||||");
    printf("\nValue of Front: %d\nValue of Rear : %d",q->f,q->r);
    printf("\n|||||||||||||||||||||||||||||||||||");
    
    Enqueue(q,98);
    Enqueue(q,83);
    Enqueue(q,24);
    Enqueue(q,35);
    
    printf("\n|||||||||||||||||||||||||||||||||||");
    printf("\nValue of Front: %d\nValue of Rear : %d",q->f,q->r);
    printf("\n|||||||||||||||||||||||||||||||||||");
    
    
    return 0;
    
}

Comments

Please sign up or log in to contribute to the discussion.