To insert a node at any position in the singly linked list using c.
PROGRAM:
#include
#include
void display();
int insert();
int insertn();
int num,loc;
char name[20];
struct node
{
int a;
char n[20];
struct node *next;
};
struct node *first,*last;
int main()
{
int ch;
do
{
printf(“\n Enter the choice \n1.display\n2.Insert\n3.insert at any position\n4.exit \n”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
display();
break;
case 2:
insert();
break;
case 3:
printf(“\n enter the location \n”);
scanf(“%d”,&loc);
insertn(loc);
break;
}
}while(ch!=4);
}
int insert()
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
printf(“\n enter val\n”);
scanf(“%d”,&temp->a);
if(first==NULL)
{
first=temp;
first->next=NULL;
}
else
{
temp->next=first;
first=temp;
}
display();
}
void append()
{
struct node *newnode;
newnode=(struct node*)malloc(sizeof(struct node));
if(newnode==NULL)
{
printf(“\n memory not allocated”);
}
printf(“\n enter the val\n”);
scanf(“%d”,&newnode->a);
printf(“\n enter the name\n”);
scanf(“%s”,newnode->n);
newnode->next=NULL;
if(first==NULL)
{
first=newnode;
}
else
{
last->next=newnode;
}
last=newnode;
}
int del(int num)
{
struct node *temp,*m;
temp=first;
while(temp!=NULL)
{
if(temp->a==num)
{
if(temp==first)
{
first=temp->next;
free(temp);
return;
}
else
{
m->next=temp->next;
free(temp);
return;
}
}
else
{
m=temp;
temp=temp->next;
}
}
}
int insertn(int loc)
{
int i;
struct node *temp,*t,*pre;
pre=first;
if(loc==1)
{
insert();
return;
}
else
{
for(i=1;i<loc;i++)
{
t=pre;
pre=pre->next;
}
temp=(struct node *)malloc(sizeof(struct node));
printf(“\n enter the value\n”);
scanf(“%d”,&temp->a);
t->next=temp;
t=temp;
t->next=pre;
pre=pre->next;
}
display();
}
int search(int num)
{
struct node *temp;
temp=first;
while(temp!=NULL)
{
if(temp->a==num)
{
printf(“%d is exist”,num);
printf(“\t its name is %s”,temp->n);
break;
}
else
temp=temp->next;
}
if(temp->a!=num)
{
printf(“not exist”);
}
}
void rev(struct node *st)
{
struct node *temp,*n,*s;
temp=st;
n=NULL;
while(temp!=NULL)
{
s=n;
n=temp;
temp=temp->next;
n->next=s;
}
first=n;
display();
}
void display()
{
struct node *temp;
temp=(struct node*)malloc(sizeof(struct node));
temp=first;
while(temp!=NULL)
{
printf(“%d\t”,temp->a);
temp=temp->next;
}
}