What is Queue with its code in c language.

What is Queue...? 


“A queue is an ordered list in which all insertions are done at one end, called rear and deletions at another end called front“ Queue

when implemented using arrays has some drawbacks which can be avoided by circular queue


An array representation of queue require three entities :

  • An array to hold queue element
  • A variable to hold index of the front element
  • A variable to hold index of the rear element

Set of operations that perform on queue : 


Code in c language of linear Queue :

/*     || LINEAR QUEUE ||

#include<stdio.h>
typedef struct Queue
{
    int a[10];
    int F,R;
} Queue;
void init (Queue *p)
{
   p->F=p->R=-1;
}
int isempty(Queue *p)
{
    if(p->R==-1)
      return 1;
      return 0;
}
int isfull(Queue *p)
{
    if(p->R==9)
      return 1;
      return 0;
}
void enqueue (Queue *p,int x)
{
    if(p->R==-1)
      p->R=p->F=0;
    else
      p->R=p->R+1;
      p->a[p->R]=x;
}
int dequeue (Queue *p)
{
    int x=p->a[p->F];
    if (p->F==p->R)
      p->F=p->R=-1;
    else 
      p->F=p->F+1;
      return x;
}
void display (Queue *p)
{
    int i=p->F;
    while(i<=p->R)
    {
        printf("%d",p->a[i]);
        i++;
    }
}

int main()
{
    Queue q;
    init(&q);
    int n,x;
    do{
        printf("\n-------------MENU-------------\n");
        printf("1.ENQUEUE\n 2.DEQUEUE\n 3.DISPLAY\n ENTER YOUR CHOICE: ");
        scanf("%d",&n);
        switch(n)
        {
          case 1:
            if (isfull(&q))
            printf("Queue is full !!!");
            else{
                printf("\n Enter element");
                scanf("%d",&x);
                enqueue (&q,x);
            }
            break;
          case 2:   
            if (isempty(&q))
            printf("\n Queue is empty"); 
            else {
                x=dequeue (&q);
                printf("%d is removed",x);
            }
            break;
          case 3:
            display(&q);
            break;
          default:
            printf("wrong choice");
        }
    }
         while(n<=3);
}







Post a Comment

Previous Post Next Post