Given a linked list, write a function to rearrange its nodes to be sorted in increasing order.

Practice this problem

The idea is to use the sortedInsert() function to sort a linked list. We start with an empty result list. Iterate through the source list and sortedInsert() each of its nodes into the result list. Be careful to note the .next field in each node before moving it into the result list.

Following is the C, Java, and Python program that demonstrates it:

C


Download  Run Code

Output:

2 —> 3 —> 4 —> 6 —> 8 —> 9 —> NULL

Java


Download  Run Code

Output:

2 —> 3 —> 4 —> 6 —> 8 —> 9 —> null

Python


Download  Run Code

Output:

2 —> 3 —> 4 —> 6 —> 8 —> 9 —> None

The time complexity of the above solution is O(n2), where n is the total number of nodes in the linked list, and doesn’t require any extra space. Please refer below for the merge sort based algorithm to sort a linked list in O(n.log(n)) time.

 
Also See:

Merge sort algorithm for a singly linked list – C, Java, and Python

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