Sorting a Singly Linked List

Given a Linked List, the task is to sort this Linked List in ascending order.

sorting image

Examples:

Input: 10->30->20->5
Output: 5->10->20->30

Input: 20->4->3
Output: 3->4->20

Approach: We can sort the LinkedList by many sorting techniques:

Method 1: Sort Linked List using Bubble Sort

  1. Get the Linked List to be sorted
  2. Apply Bubble Sort to this linked list , in which, while comparing the two adjacent nodes, actual nodes are swapped instead of just swapping the data.
  3. Print the sorted list

Below is the implementation of the above approach:

                                                                                                                     "                                                                              Java
                                                                                "                                                                             Python
JavaScript
Output
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)

Method 2: Sort Linked List using Insertion Sort

Below is a simple insertion sort algorithm for a linked list.