Solution using C language:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int info;
struct node*link;
};
void insert_front(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
{
temp->link=*p;
*p=temp;
}
}
void delete_front(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=q;
r=r->link;
free(q);
*p=r;
}
}
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_front 2.Delete _front 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_front(&first,item);
}
break;
case 2:{
delete_front(&first);
}
break;
case 3:{
display(first);
}
break;
case 4:exit(0);
}
}
while(ch);
return 0;
}
Output:
1.Insert_front 2.Delete _front 3.Display 4.Exit
Enter your choice
1
Enter the item to be inserted
5
1.Insert_front 2.Delete _front 3.Display 4.Exit
Enter your choice
3
5 1.Insert_front 2.Delete _front 3.Display 4.Exit
Enter your choice
2
1.Insert_front 2.Delete _front 3.Display 4.Exit
Enter your choice
4
No comments:
Post a Comment