20. Program for implementing
queue using linked list?
Program
#include<stdio.h>
#include<conio.h>
struct node //declaring the structure of linked list
{
int data;
struct node *link;
}*front=NULL,*rear=NULL;
void ins() //Insert operation
{
struct node *temp;
int item;
temp=(struct node *)malloc(sizeof(struct node));
printf("Enter the element to be inserted:\t");
scanf("%d",&item);
temp->data=item;
temp->link=NULL;
if(front==NULL) //if list is empty
front=temp;
else
rear->link=temp;
rear=temp;
}
void del() //deletion operation
{
struct node *temp;
if(front==NULL) //if list is empty
printf("\tQueue underflow\n");
else
{
temp=front;
printf("The deleted element is %d\n",temp->data);
front=front->link;
free(temp);
}
}
void display()
{
struct node *ptr;
ptr=front;
if(front==NULL)
printf("The stack is empty\n");
else
{
printf("The Queue elements are:\n");
while(ptr!=NULL)
{
printf("%d\t",ptr->data);
ptr=ptr->link;
}
}
}
void main()
{
int ch,i;
char c;
clrscr();
do
{
printf("Enter the choice\t1.Insertion\t2.Deletion\t3.Display\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
ins(); //calling insertion function
break;
case 2:
del(); //calling deletion function
break;
case 3:
display(); //calling display function
break;
default:
printf("\nWRONG CHOICE\n");
break;
}
printf("\nDo you want to continue:(y/n)?\n");
scanf(" %c",&c);
}
while((c=='y')||(c=='Y'));
getch();
}
Output
Enter the choice 1.Insertion 2.Deletion 3.Display
1
Enter the element to be inserted: 1
Do you want to continue:(y/n)?
y
Enter the choice 1.Insertion 2.Deletion 3.Display
1
Enter the element to be inserted: 2
Do you want to continue:(y/n)?
y
Enter the choice 1.Insertion 2.Deletion 3.Display
3
The Queue elements are:
1 2
Do you want to continue:(y/n)?
y
Enter the choice 1.Insertion 2.Deletion 3.Display
2
The deleted element is 1
Do you want to continue:(y/n)?
y
Enter the choice 1.Insertion 2.Deletion 3.Display
3
The Queue elements are:
2
Do you want to continue:(y/n)?
y
Enter the choice 1.Insertion 2.Deletion 3.Display
2
The deleted element is 2
Do you want to continue:(y/n)?
y
Enter the choice 1.Insertion 2.Deletion 3.Display
3
The stack is empty
Do you want to continue:(y/n)?
y
Enter the choice 1.Insertion 2.Deletion 3.Display
2
Queue underflow
Do you want to continue:(y/n)?
n
No comments:
Post a Comment