Implementation of Queue using ARRAY method-1

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

struct Queue{
  int size;
  int front;
  int rear;
  int *arr;
};

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

int isEmpty(struct Queue *ptr){
    if(ptr->front == ptr->rear){
        return 1;
    }
    return 0;
}

int isFull(struct Queue *ptr){
    if(ptr->rear == ptr->size-1){
        return 1;
    }
    return 0;
}

void enqueue(struct Queue *ptr,int element){
    if(isFull(ptr)){
        printf("\nQueue OverFlow!");
    }
    else{
        ptr->rear++;
        ptr->arr[ptr->rear] = element;
    }
}

int dequeue(struct Queue *ptr){
    if(isEmpty(ptr)){
        printf("\nQueue UnderFlow!");
    }
    else{
        int result = ptr->arr[ptr->front+1];
        ptr->front++;
        return result;
    }
    return -1;
}

// int peek(struct Queue *ptr,int pos){
    
// }

int main() {
    
    struct Queue *q = (struct Queue*)malloc(sizeof(struct Queue));
    q->size = 10;
    q->front = -1;
    q->rear = -1;
    q->arr = (int *)malloc(q->size*sizeof(int));
    
    enqueue(q,54);
    enqueue(q,65);
    enqueue(q,89);
    enqueue(q,98);
    enqueue(q,112);
    enqueue(q,54);
    printf("Before Delete the element: \n");
    traversal(q);
    
    printf("Deleted Element is : %d\n",dequeue(q));
    printf("Deleted Element is : %d\n",dequeue(q));
    printf("Deleted Element is : %d\n",dequeue(q));
    
    printf("After Delete the element: \n");
    traversal(q);
    return 0;
}

Comments

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