Advertisment

Inserting a node

author-image
CIOL Bureau
Updated On
New Update





You could insert a new node in three places; at the beginning of the list,
in the middle of the list between two nodes or at the end of the list.

The example given here is to be integrated with the previous tutorial on creating

a link list
. The function insert() requests for the node number where the

new node has to be inserted. If the insertion happens to be at the beginning,

then memory space is created for the new node, the value of the new item is

assigned to it and the pointer head is assigned to the next member. The pointer

new, which indicates the beginning of the new node, is assigned to head. However

if the new item is to be inserted between two nodes then we use the find()

function recursively to locate the node and the new item is inserted after this

node.

Advertisment

#include



main()


{


node *ptr;


char ans='y';


void create(node *p),print(node *y),insert(node *q);


int count(node *x);




ptr=(node *)malloc(sizeof(node));



create(ptr);


printf("\nPrinting the elements of the list");


print(ptr);


printf("\nThe number of items in the list are = %d",count(ptr));


/* Additional code to be inserted with the previous tutorial on creating a
link list
*/



printf("\nDo you want to insert a record ");



getchar();


scanf("%c",&ans);


if(ans=='y')


{


insert(ptr);


}


}





void insert(node *pt)



{


node *new,*n,*find(node *m,int n);


int nodenum;


char ans;





printf("\nEnter the node number where the new record has to be inserted
:");



scanf("%d",&nodenum);


new=(node *)malloc(sizeof(node));


printf("\nEnter the record number,name & age:");


scanf("%d %s %d",&new->num,new->name,&new->age);


if(r->num==nodenum)


{


new->next=pt;


pt=new;


print(pt);


}


else


{


n=find(pt,nodenum);


new->next=n->next;


n->next=new;


print(pt);


}


printf("\nWould you like to insert another record :");


getchar();


scanf("%c",&ans);


if(ans=='y')


{


insert(pt);


}


else


{


print(pt);


}


}

































node *find(node *x,int y)



{


if(x->num==y)


{


return(x->next);


}


else if(x->next==0)


{


printf("\nNode not found");


return;


}


else


{


find(x->next,y);


}


}













tech-news