Tuesday, 23 August 2016

Queue implementation using array

//Girfa Student Help
// For More DS Program Visit
// http://girfahelp.blogspot.in/p/data.html
#include<stdio.h>
#include<conio.h>
#define MAX 5
void main()
{
int ar[MAX],front=-1,rear=-1,opt,n;
do
{
clrscr();
printf("\n1. Enqueue\n2. Dequeue\n3. Print\n0. Exit\nEnter your choice>> ");
scanf("%d",&opt);
switch(opt)

{
case 1:
printf("\nEnter number>> ");
scanf("%d",&n);
if(front==-1 && rear==-1)//first element
{
front=rear=0;
ar[rear]=n;
}
else
{
if((front==0 && rear==MAX-1) || (rear+1==front))
{
printf("\n\tQueue is full");
getch();
}
else
{
if(rear==MAX-1)//if queue is not fully filled and queue is not empty
rear=0;
else
rear++;
ar[rear]=n;
} }

break;
case 2:
if(rear==-1 && front==-1)
printf("\nQueue is empty");
else
{
if(front==MAX)
{
front=0;
n=ar[MAX-1];
}
else if(front==rear) // if queuq has only one item
{
n=ar[front];
front=rear=-1;
}
else
{
n=ar[front++];
}
printf("\nQueued number is %d",n);
}
getch();
break;
case 3:
if(front==-1 && rear==-1)
printf("\nList is Empty");
else
{
if(rear>front)
{
for(n=front;n<=rear;n++)
printf("\t%d",ar[n]);
}
else
{
for(n=front;n<MAX;n++)
printf("\t%d",ar[n]);
for(n=0;n<=rear;n++)
printf("\t%d",ar[n]);
}
}
getch();
break;
case 0:
break;
default:
printf("\nInvalid Option");
getch();
}
}while(opt!=0);
}

Next Program