Courses βeta
Data Structures

## Sorted Insert in a Linked List

Algorithm:
Let input linked list is sorted in increasing order.

1. If Linked list is empty then make the node as head and return it.

2. If value of the node to be inserted is smaller than value of head node

then insert the node at start and make it head.

3. In a loop, find the appropriate node after which the input node (let 9) is

to be inserted. To find the appropriate node start from head, keep moving

until you reach a node GN (10 in the below diagram) who's value is

greater than the input node. The node just before GN is the appropriate

node (7).

4. Insert the node (9) after the appropriate node (7) found in step 3.

Linked List after insertion of 9

Implementation:

/* Program to insert in a sorted list */
#include<stdio.h>
#include<stdlib.h>

struct node
{
int data;
struct node* next;
};

/* function to insert a new_node in a list. Note that this
function expects a pointer to head_ref as this can modify the
void sortedInsert(struct node** head_ref, struct node* new_node)
{
struct node* current;
/* Special case for the head end */
{
}
else
{
/* Locate the node before the point of insertion */
while (current->next!=NULL &&
current->next->data < new_node->data)
{
current = current->next;
}
new_node->next = current->next;
current->next = new_node;
}
}

/* BELOW FUNCTIONS ARE JUST UTILITY TO TEST sortedInsert */

/* A utility function to create a new node */
struct node *newNode(int new_data)
{
/* allocate node */
struct node* new_node =
(struct node*) malloc(sizeof(struct node));

/* put in the data  */
new_node->data  = new_data;
new_node->next =  NULL;

return new_node;
}

/* Function to print linked list */
{
while(temp != NULL)
{
printf("%d  ", temp->data);
temp = temp->next;
}
}

/* Drier program to test count function*/
int main()
{
struct node *new_node = newNode(5);
new_node = newNode(10);
new_node = newNode(7);
new_node = newNode(3);
new_node = newNode(1);
new_node = newNode(9);

return 0;
}