Algo DS: Circular Queue

 

code:

#include<stdio.h>
#define size 4
int q[size];
int rear=-1;
int front=-1;

Enqueue(int item){
    if((rear+1)%size==front){
        printf("Queue Overflow\n");
    }else{
        if(rear==-1 && front==-1)
        {
            rear=0;
            front=0;
        }
        else{
            rear=(rear+1)%size;
        }
        q[rear]=item;
        printf("%d is inserted\n",item);
    }
}

 Dequeue(){
    int value;
    if(rear==-1 && front==-1)
    {
        printf("Queue underflow\n");
        return -1;
    }
    else{
        value=q[front];
        if(rear==front)
        {
            rear=-1;
            front=-1;
        }
        else{
            front=(front+1)%size;
        }
        return value;
    }
}

void Display()
{
    int i;
    if(rear==-1 && front==-1)
    {
        printf("Queue is empty\n");
    }
    else{
        if(front<=rear)
        {
            for(i=front;i<=rear;i++)
            {
                printf("q[%d]=%d\n",i,q[i]);
            }
        }
        else{
            for(i=front;i<size-1;i++)
            {
                printf("q[%d]=%d\n",i,q[i]);
                for(i=0;i<=rear;i++)
                {
                    printf("q[%d]=%d\n",i,q[i]);
                }
            }
        }
    }


}

int main()
{
    int cho,n;
    do{
        printf("press 1 for queue\n");
        printf("press 2 for dequeue\n");
        printf("press 3 for display\n");
        printf("press 4 for exit\n");
        printf("Enter your choice: ");
        scanf("%d",&cho);
        switch(cho)
        {
        case 1:

            printf("Enter item to insert: ");
            scanf("%d",&n);
            Enqueue(n);
            break;
        case 2:
            Dequeue();
            break;
        case 3:
            Display();
            break;
        }

    }while(cho!=4);


    return 0;
}

It would be a great help, if you support by sharing :)
Author: zakilive

Leave a Reply

Your email address will not be published.