Program code for inserting node at any position in Linked List

//C Program code for inserting new node at  any position you like

#include<stdio.h>
#include<conio.h>
#include<alloc.h>

typedef struct linked
{
int val;
struct linked *next;
}lnk;

lnk *insert(lnk *,int,int);
void disp(lnk *);

void main()
{
lnk *h=NULL;
int ch,pos,v;

while(1)
{
printf("\n1) Insert at any position \n2) Display \n3) Exit");
printf("\nEnter your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\n Enter the value : ");
scanf("%d",&v);
printf("\n Enter the posiotion of new node : ");
scanf("%d",&pos);
h=insert(h,v,pos);
break;
case 2: printf("\n\nValues are :");
disp(h);
break;
case 3: exit(0);
default: printf("\n\nWrong choice");
}
}
}

lnk *insert(lnk *h,int v,int po)
{
lnk *ptr,*temp,*pre;
int i;
temp=(lnk*)malloc(sizeof(lnk));
temp->val=v;
temp->next=NULL;
if(h==NULL)
{
printf("\nThis is your first node so this node has become head ");
h=temp;
}
else
{
if(po==1)
{
temp->next=h;
h=temp;
}
else
{
i=1;
ptr=h;
while(i<po && ptr!=NULL)
{
pre=ptr;
ptr=ptr->next;
i++;
}
if(ptr==NULL)
{
printf("\nThis position is not available so it will become the last node");
}
temp->next=pre->next;
pre->next=temp;
}
}
return h;
}

void disp(lnk *h)
{
lnk *ptr;
ptr=h;
while(ptr!=NULL)
{
printf("%d,",ptr->val);
ptr=ptr->next;
}
}

Comments

Popular posts from this blog

JAVA program to add two distance

Print Pattern using C