Sunday 22 January 2017

C program to Implement Queue using linked list

#include <stdio.h>

#include <stdlib.h>
struct Q
{

   int data;

   struct Q *next;

};



void enq(struct Q **,struct Q **);

void deq(struct Q **, struct Q **);

void display(struct Q *,struct Q *);

main()

{

     struct Q *front =NULL, *rear=NULL;

     int n,i;

     printf("enter the number of elements");

     scanf("%d",&n);

     for(i=1;i<=n;i++)

          enq(&front,&rear);

     display(front,rear);

     deq(&front,&rear);

     printf("\n After deleting one element\n");

     display(front,rear);

}

void enq(struct Q **front,struct Q **rear)

{

     int val;

     struct Q *newnode =(struct Q *)malloc(sizeof(struct Q));

     printf("enter a value");

     scanf("%d",&val);

     newnode->data=val;

     newnode->next=NULL;

     if(*front == NULL )

         *front = *rear = newnode;

     else

     {

         (*rear)->next=newnode;

         *rear=newnode;

     }

}



void display(struct Q *front,struct Q *rear)

{

        if(front == NULL)

              printf("queue empty");

        else

        {

              while(front != NULL)

              {

                    printf("%d->",front->data);

                    front=front->next;

              }

        }

}

void deq(struct Q **front, struct Q **rear)

{

          if(*front == NULL)

                printf("queue is empty");

          else

         {

                 if(*front == *rear)

                      *front = *rear = NULL;

                 else

                      *front=(*front)->next;

         }

}


No comments:

Post a Comment