Solution:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *front=NULL;
struct node *rear=NULL;
struct node *cn()
{
struct node *n;
n=(struct node *)malloc(sizeof(struct node));
return(n);
}
void createqueue()
{
int n,x,i;
struct node *newnode;
printf("Enter size of queue :\n");
scanf("%d",&n);
printf("Enter elements of queue :\n");;
for(i=1;i<=n;i++)
{
scanf("%d",&x);
if(front==NULL)
{
newnode=cn();
newnode->data=x;
newnode->next=NULL;
front=newnode;
rear=newnode;
}
else
{
newnode=cn();
newnode->data=x;
rear->next=newnode;
newnode->next=NULL;
rear=newnode;
}
}
}
void insert()
{
struct node *newnode;
int x;
printf("Enter element:\n");
scanf("%d",&x);
newnode=cn();
newnode->data=x;
newnode->next=NULL;
if(front==NULL)
{
front=newnode;
rear=newnode;
}
else
{
rear->next=newnode;
rear=newnode;
}
printf("Element inserted successfully");
}
void delete()
{
struct node *temp;
if(front==NULL)
{
printf("Queue is empty.\n");
}
else
{
temp=front;
front=front->next;
temp->next=NULL;
free(temp);
}
printf("Element deleted successfully");
}
void display()
{
struct node *temp;
temp=front;
printf("\n");
while(temp->next!=NULL)
{
printf("%d\n",temp->data);
temp=temp->next;
}
printf("%d\n",temp->data);
}
void main()
{
int choice,a=0;
while(choice!=5)
{
printf("\n\n1. Create queue\n");
printf("2. Insert\n");
printf("3. Delete\n");
printf("4. Display\n");
printf("5. Exit\n\n");
scanf("%d",&choice);
switch(choice)
{
case 1: if(a==1)
{
printf("You have already create queue.\n");
}
else
{
createqueue();
a=1;
}
break;
case 2: insert();
break;
case 3: delete();
break;
case 4: display();
break;
case 5: exit(0);
deafult:printf("Enter valid choice.");
}
}
}
0 Comments