To insert a node in a specific location of a previously created linked list- you have to select the location where to insert the node. Next step is to traverse through the linked list and connect the new node when the specified location is reached.
# include < stdio.h>
# include < stdlib.h>
struct link
{
int info;
struct link *next;
};
int i;
int number;
struct link *start=NULL, *p, *new1,*node;
void create()
{
char ch;
i=1;
start = (struct link* ) malloc(sizeof(struct link));
printf("\n Enter value for node: %d: ",i);
scanf("%d", &start->info);
fflush(stdin);
start->next = NULL;
node=start;
printf("\n Input choice n for break: ");
ch = getche();
while(ch != 'n')
{
i=i+1;
node->next = (struct link* ) malloc(sizeof(struct link));
node = node->next;
printf("\n Enter value for node: %d: ",i);
scanf("%d", &node->info);
node->next = NULL;
printf("\n Input choice n for break: ");
ch = getche();
}
printf("\n Total nodes = %d", i);
}
void insertion()
{
int x=0;
int number = 1;
int insert;
p = start;
node = p->next;
do
{
if(x!=0)
{
clrscr();
printf("Enter the position properly.");
}
printf("\n Input the location ( in numeric) where you want to insert");
printf("\n the newly created node-Value should be less or equal to the");
printf("\n number of nodes in the list: ");
scanf("%d", &insert);
x++;
}while((insert<1)||(insert>i));
while(node)
{
if(number == insert)
{
new1 = (struct link* ) malloc(sizeof(struct link));
new1->next = node;
p->next = new1;
printf("\n Input the node value: ");
scanf("%d", &new1->info);
break ;
}
else
{
node = node->next;
p= p->next;
}
number ++;
}
}
void display()
{
node = start;
while (node)
{
printf(" %d", node->info);
node = node->next;
}
}
void main()
{
clrscr();
create();
printf("\n Created list is as follows:\n");
display();
insertion();
printf("\n After Inserting a node list is as follows:\n");
display();
getch();
}
In this above program, creation of the linked list is same as the above program. One thing I have done in this program, while creating the linked list – number of nodes are counted. It will help us while taking the location of insertion in the linked list from the user.
The location of inserting in the linked list is taken from the user with great care. The input statement for location is kept inside a do while loop and it is made sure that the location exists in the linked list.
The moving pointers of the linked list, ‘node’ and ‘p’ are made to point the 2nd node and the 1st node of the linked list respectively. On traversal of the list the new node is inserted in specific location.
No comments:
Post a Comment