Wednesday 8 February 2017

C program to implement Queue using single linked list by using global variables

#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *f=NULL,*r = NULL,*c;
void enq();
void deq();
void display();
main()
{
          int opt;
while(1)
         {
printf("\n Press 1. Enq\t 2. Deq\t 3. Display \t 4. Exit\n");
               scanf("%d",&opt);
               switch(opt)
             {
                 case 1: enq();
                            break;
                 case 2: deq();
                            break;
                 case 3: display();
                            break;
case 4: exit(0);
            }
        }
}
void enq()
{
int val;
printf("enter value to be enqueued\n");
scanf("%d",&val);
struct node *newnode = (struct node *)malloc(sizeof(struct node));
newnode->data=val;
newnode->next=NULL;
if(f == NULL && r == NULL)
f=r=newnode;
else
{
r->next=newnode;
r= newnode;
}
}

void deq()
{
if(f == NULL && r == NULL)
{
printf("queue is empty");
return;
}
if(f = = r)
       f = r = NULL;
else
{
c=f;
f=f->next;
free(c);
}
}

void display()
{
if(f == NULL && r == NULL)
{
printf("queue is empty");
return;
}
else
{
c=f;
while(c != NULL)
{
printf("%d\t",c->data);
c=c->next;
}
}
}


No comments:

Post a Comment