Given a Linked List, the task is to sort this Linked List in ascending order.
Examples:
Input: 10->30->20->5
Output: 5->10->20->30Input: 20->4->3
Output: 3->4->20
Approach: We can sort the LinkedList by many sorting techniques:
Below is the implementation of the above approach:
" <span Create linked list from the array arr[] */ Java
" <span Create linked list from the array arr[] Python
JavaScript
Linked list before sorting 78 -> 20 -> 10 -> 32 -> 1 -> 5 -> Linked list after sorting 1 -> 5 -> 10 -> 20 -> 32 -> 78 ->
Time complexity: O(n ^ 2)
Auxiliary Space: O(1)
Below is a simple insertion sort algorithm for a linked list.
Below is the implementation of the above approach:
Java
Python
JavaScript
Linked List before sorting 30 3 4 20 5 Linked List After sorting 3 4 5 20 30
Time complexity: O(n ^ 2)
Auxiliary Space: O(1)
Below is the implementation of the above approach:
<span Create dynamic node <span Create linked list Java
Python
JavaScript
Linked List before sorting 30 3 4 20 5 Linked List after sorting 3 4 5 20 30
Time complexity: O(n ^ 2)
Auxiliary Space: O(1)
Let the head be the first node of the linked list to be sorted and headRef be the pointer to head. Note that we need a reference to head in MergeSort() as the below implementation changes next links to sort the linked lists (not data at the nodes), so the head node has to be changed if the data at the original head is not the smallest value in the linked list.
Below is the implementation of the above approach:
a or b, and recur */ <span Start with the empty list */ 3->20->5->10->15 */ C
a or b, and recur */ <span Start with the empty list */ 3->20->5->10->15 */ Java
a or b, and recur <span Start with the empty list 3->20->5->10->15 Python
a or b and recur.. span set the next of middle node to None 3->20->5->10->15 C#
a or b, and recur <span Start with the empty list 3->20->5->10->15 JavaScript
Sorted Linked List is: 2 3 5 10 15 20
Time complexity: O(n log n)
Auxiliary Space: O(1)