Given a sorted list in increasing order and a single node, insert the node into the list’s correct sorted position. The function should take an existing node and rearranges pointers to insert it into the list.

For example,

sortedinsert

Practice this problem

There are many possible solutions to this problem. The basic strategy is to iterate down the list looking for the place to insert the new node. That could be the end of the list or a point just before a larger node than the new node. The three solutions presented handle the “head end” case in different ways.

1. Naive Approach

The naive implementation can be seen below in C, Java, and Python:

C


Download  Run Code

Output:

1 —> 2 —> 4 —> 5 —> 6 —> 8 —> 9 —> NULL

Java


Download  Run Code

Output:

1 —> 2 —> 4 —> 5 —> 6 —> 8 —> 9 —> null

Python


Download  Run Code

Output:

1 —> 2 —> 4 —> 5 —> 6 —> 8 —> 9 —> None

2. Using Dummy Node

Another strategy is to use a temporary dummy node to take care of the first node case – the dummy node nothing but temporarily the first node in the list. Following is the C, Java, and Python program that demonstrates it:

C


Download  Run Code

Output:

1 —> 2 —> 4 —> 5 —> 6 —> 8 —> 9 —> NULL

Java


Download  Run Code

Output:

1 —> 2 —> 4 —> 5 —> 6 —> 8 —> 9 —> null

Python


Download  Run Code

Output:

1 —> 2 —> 4 —> 5 —> 6 —> 8 —> 9 —> None

3. Using Local references

Finally, we can use also use local references to insert a node into the list’s correct sorted position. The implementation can be seen below in C:

C


Download  Run Code

Output:

1 —> 2 —> 4 —> 5 —> 6 —> 8 —> 9 —> NULL

The time complexity of the above solution is O(n), where n is the total number of nodes in the linked list, and doesn’t require any extra space.

 
Source: http://cslibrary.stanford.edu/105/LinkedListProblems.pdf