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:
" Java
" 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
<span Allocate a new node 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:
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:
<span Created lists shall be a: 2->3->20->5->10->15 */ C
<span Created lists shall be a: 2->3->20->5->10->15 */ Java
<span Created list shall be a: 2->3->20->5->10->15 Python
<span Python3 program to merge sort of linked list middle of the list 3->20->5->10->15 C#
<span Created list shall be: 2->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)