Insertion in singly linked list after specified Node
- To insert an element into a linked list after a certain number of nodes, we must skip the desired number of elements in the list and change the pointer to the spot where the node will be put.
- The following statements will be used to do this.
emp=head;
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL)
{
return;
}
}
- Allocate space for the new node and include the item in the data section. The following statements will be used to do this.
ptr = (struct node *) malloc (sizeof(struct node));
ptr->data = item;
- Only a few more link adjustments are needed, and our node will be put at the correct location.
- Because the loop pointer temp will be pointing to the node when the new node is placed at the end of the loop.
- As a result, the address of the next portion of the temp must be included in the next part of the new node ptr (since, ptr will be in between temp and the next of the temp).
- The following statements will be used to do this.
ptr→ next = temp → next
- Now, we just need to make the next part of the temp, point to the new node ptr. This will insert the new node ptr, at the specified position.
temp ->next = ptr;
Algorithm
- STEP 1: IF PTR = NULL
GOTO STEP 12
END OF IF
- STEP 2: SET NEW_NODE = PTR
- STEP 3: NEW_NODE → DATA = VAL
- STEP 4: SET TEMP = HEAD
- STEP 5: SET I = 0
- STEP 6: REPEAT STEP 5 AND 6 UNTIL I
- STEP 7: TEMP = TEMP → NEXT
- STEP 8: IF TEMP = NULL
GOTO STEP 12
END OF IF
END OF LOOP
- STEP 9: PTR → NEXT = TEMP → NEXT
- STEP 10: TEMP → NEXT = PTR
- STEP 11: SET PTR = NEW_NODE
- STEP 12: EXIT
C program to insert data(after specific node) in singly linked list.
#include<stdio.h>
#include<stdlib.h>
void randominsert(int);
void create(int);
struct node
{
int data;
struct node *next;
};
struct node *head;
void main ()
{
int choice,item,loc;
do
{
printf("\nEnter the item which you want to insert?\n");
scanf("%d",&item);
if(head == NULL)
{
create(item);
}
else
{
randominsert(item);
}
printf("\nPress 0 to insert more ?\n");
scanf("%d",&choice);
}while(choice == 0);
}
void create(int item)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node *));
if(ptr == NULL)
{
printf("\nOVERFLOW\n");
}
else
{
ptr->data = item;
ptr->next = head;
head = ptr;
printf("\nNode inserted\n");
}
}
void randominsert(int item)
{
struct node *ptr = (struct node *) malloc (sizeof(struct node));
struct node *temp;
int i,loc;
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("Enter the location");
scanf("%d",&loc);
ptr->data = item;
temp=head;
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL)
{
printf("\ncan't insert\n");
return;
}
}
ptr ->next = temp ->next;
temp ->next = ptr;
printf("\nNode inserted");
}
}
Expected Output:
Enter the item which you want to insert?
12
Node inserted
Press 0 to insert more ?
2