Saturday, 4 March 2017

C program to implement queue using linklist.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct stack
{
int info;
struct stack *next;
}s;
s *front=NULL;
s *rear=NULL;
void push(s *,int);
int pop(s *);
void display(s *);
main()
{
int item,choice;
while(1)
{
printf("\n    ***********\n    1.)push\n    2.)pop\n    3.)display\n    4.)exit\n    Enter your choice : ");
   scanf("%d",&choice);
switch(choice)
{
case 1:
  printf("enter item to be push :");
  scanf("%d",&item);
  push(rear,item);
  break;
case 2:
      item=pop(front);
  printf("popped item is : %d",item);
  break;
case 3:
      display(front);
  break;
case 4:
      exit(1);
  break;
default:
      printf("please enter your choice again");        
}
}
getch();
}
void push(s *p,int item)
{
s*tmp;
tmp=(s *)malloc(sizeof(s));
if(p==NULL)
{
tmp->info=item;
rear=tmp;
rear->next=NULL;
front=tmp;
}
else
{
tmp->info=item;
rear->next=tmp;
rear=tmp;
rear->next=NULL;

}
}
void display(s *p)
{
s *ptr;
ptr=front;
if(front==NULL)
{
printf("queue is empty");
exit(1);
}
else
    {
printf("queue is\n");
printf("       | ");
while(ptr->next!=NULL)
{
printf("%d ",ptr->info);
ptr=ptr->next;
}
printf("%d ",ptr->info);
printf(" | ");
    }
}
int pop(s *p)
{int item;
if(front==NULL)
{
printf("queue is empty");
exit(1);
}
s*tmp;
tmp=front;
item=tmp->info;
front=front->next;
free(tmp);
return item;
}

No comments:

Post a Comment