C Program to implement a Queue...

#include<stdio.h>
#define maxi 5

struct queue // Structure of a Queue...
{
 int a[maxi];
 int f,r;
};

int flag;  // Temporary variable to handle the error condition in delete function...

void insert(struct queue *p,int x);
int delete(struct queue *p);
void display(struct queue q);

void main()
{
 struct queue q;
 int temp,breakcondition=0; // Temporary variable breakcondition to exit the menu driven program...
 q.f=q.r=-1;
 printf("\nChoice: 1)Insertion 2)Deletion 3)Display 4)Stop..");
 int ch;
 while(1)
 {
  printf("\nEnter your choice..");
  scanf("%d",&ch);
  switch(ch)
  {
   case 1:{
           int temp;
           printf("\nEnter any element..");
           scanf("%d",&temp);
           insert(&q,temp);
           break;
          }
   case 2:{ flag=0;
            int temp=delete(&q);
            if(flag==0)
            printf("\nThe element which is deleted is..%d",temp);
           break;
          }
   case 3:{
           display(q);
           break;
          }
   case 4:{
           breakcondition=1;
           break;
          }
   default:printf("\nPlease enter a valid choice..");
  }
 if(breakcondition==1)
   break;
 }
}

void insert(struct queue *p,int x)
{
 if(p->r==maxi-1){                   // Corner Case to handle if the queue is full...
  printf("\nQueue Overflow..");
  return;
 }
 else if(p->r==-1&&p->f==-1){  // Corner Case to handle if the queue is empty...
  p->r=p->f=0;
  p->a[p->r]=x;
 }
 else{
 p->a[++p->r]=x;
 }
}

int delete(struct queue *p)
{
 int x;
 if(p->f==-1&&p->r==-1)  // Corner Case to handle if the queue is empty...
  {
   flag=1;
   printf("\nThe Queue is Already Empty..");
  }
 else if (p->f==p->r){  // Corner Case to handle if the queue contains only one element...
  x=p->a[p->f];
  p->f=p->r=-1;
 }
else{
  x=p->a[p->f++];
 }
return x;
}

void display(struct queue q)
{
 if(q.f==-1){           // Corner Case to handle if the queue is empty...
   printf("\nQueue is empty..");
   return;
 }
 printf("\nThe Elements of Queue are..\n");
 while(q.f!=-1)     // Deleting all the nodes of the local queue(copy of the original)  and displaying them...
 {
 printf("%d\n",delete(&q));
 }
}

No comments:

Post a comment