You need to find a node after which we can insert
Iterative code
void sortedInsert(struct node** head_ref, struct node* new_node)
{
struct node* current;
/* Special case for the head end */
if (*head_ref == NULL || (*head_ref)->data >= new_node->data)
{
new_node->next = *head_ref;
*head_ref = new_node;
}
else
{
/* Locate the node before the point of insertion */
current = *head_ref;
while (current->next!=NULL &&
current->next->data < new_node->data)
{
current = current->next;
}
new_node->next = current->next;
current->next = new_node;
}
}
Recursive code
void sortedInsertRecursive(struct node **head_ref, struct node* new_node)
{
struct node* current;
/* Special case for the head end */
if ((*head_ref) == NULL || (*head_ref)->data >= new_node->data)
{
new_node->next = *head_ref;
(*head_ref) = new_node; // Its double pointer case so it should correct the parent pointer
}
else
{
/* Locate the node before the point of insertion */
if ((*head_ref)->next != NULL &&
(*head_ref)->next->data < new_node->data)
{
sortedInsertRecursive((*head_ref)->next, new_node);
}
}
}