Problem of the day
For a given Singly Linked List of integers, sort the list using the 'Merge Sort' algorithm.
The first and the only line of input contains the elements of the linked list separated by a single space.
Remember/Consider :
While specifying the list elements for input, -1 indicates the end of the singly linked list and hence, would never be a list element
Output format :
The only line of output contains the sorted elements of the Singly Linked List in a row, separated by a single space.
Note:
You are not required to print the elements, just sort the elements and return the head to the updated Singly Linked List.
1 <= N <= 10^5
1 <= DATA <= 10^9
Where 'DATA' denotes the value of node of Linked List.
Time Limit: 1sec
1 4 5 2 -1
1 2 4 5
10 9 8 7 6 5 4 -1
4 5 6 7 8 9 10
If you know the merge sort algorithm for an array, can you extend the same idea to a LinkedList? Think of the changes when you have a LinkedList in place of an array. For example, we cannot get the middle element of the LinkedList directly.
O(N * logN), where N is the size of the Singly Linked List.
Recurrence Relation: T(N) = 2T(N/2) + N*K (K is a constant)
O(log N), where N is the size of the Singly Linked List.
Since we use the recursion stack and at max, we make log (base2) N function calls.