A Node can be created in three positions of a linked list:
1. At the end of the List
2. At the beginning of the List
3. At any desired position in the List.
_________________________________________________________________________________
1. The function of adding a node at the end of the list is below:
void add_node(int data)
{
Node *newptr=NULL;
Node *ptr;
newptr=(Node*)malloc(sizeof(Node));
newptr->info=data;
newptr->link=NULL;
if(start==NULL)
{
start=newptr;
}
else
{
ptr=start;
while(ptr->link!=NULL)
{
ptr=ptr->link;
}
ptr->link=newptr;
}
}
_________________________________________________________________________________
2. The function of adding a node at the beginning of the list is below:
void add_beg(int value) { Node *newp=NULL; newp=(Node*)malloc(sizeof(Node)); newp->info=value; newp->Link=NULL; if(start==NULL) { start=newp; } else { newp->Link=start; start=newp;
} }
_________________________________________________________________________________
3. The function of adding a node at any desired position in the list is below:
void add_anyposition(int value,int pos)
{
Node *newp=NULL,*tptr=start;
int steps=1;
newp=(Node*)malloc(sizeof(Node));
newp->info=value;
newp->Link=NULL;
while(steps<pos-1)
{
tptr=tptr->Link;
steps++;
}
if(pos==1)
{
newp->Link=start;
tptr->Link=newp;
}
else
{
newp->Link=tptr->Link;
tptr->Link=newp;
}
}
Comments