Solution using C language:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int info;
struct node*link;
};
void insert_rear(struct node **p,int item)
{
struct node *temp;
temp=(struct node*)malloc(sizeof(struct node));
temp->link=NULL;
temp->info=item;
if(*p==NULL)
{
*p=temp;
}
else
{
struct node *q;
q=*p;
while(q->link!=NULL)
{
q=q->link;
}
q->link=temp;
}
}
void delete_rear(struct node **p)
{
struct node *q;
q=*p;
if(q==NULL)
{
printf("No nodes to delete\n");
exit(0);
}
else if(q->link==NULL)
{
free(q);
*p=NULL;
}
else
{
struct node *r;
r=NULL;
while(q->link!=NULL)
{
r=q;
q=q->link;
}
free(q);
r->link=NULL;
}
}
void display(struct node *p)
{
while(p!=NULL)
{
printf("%d ",p->info);
p=p->link;
}
}
int main()
{
int ch;
struct node *first=NULL;
int item;
do
{
printf("1.Insert_rear 2.Delete _rear 3.Display 4.Exit\n");
printf("Enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:{
printf("Enter the item to be inserted\n");
scanf("%d",&item);
insert_rear(&first,item);
}
break;
case 2:{
delete_rear(&first);
}
break;
case 3:{
display(first);
}
break;
case 4:exit(0);
}
}
while(ch);
return 0;
}
Output:
1.Insert_rear 2.Delete _rear 3.Display 4.Exit
Enter your choice
1
Enter the item to be inserted
4
1.Insert_rear 2.Delete _rear 3.Display 4.Exit
Enter your choice
1
Enter the item to be inserted
5
1.Insert_rear 2.Delete _rear 3.Display 4.Exit
Enter your choice
2
1.Insert_rear 2.Delete _rear 3.Display 4.Exit
Enter your choice
3
4 1.Insert_rear 2.Delete _rear 3.Display 4.Exit
Enter your choice
4
No comments:
Post a Comment