Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Merge Sort Linked List

Moderate
0/80
Average time to solve is 10m
profile
Contributed by
38 upvotes
Asked in companies
AdobeGoogleSamsung R&D Institute

Problem statement

You are given a Singly Linked List of integers. Sort the Linked List using merge sort.

Merge Sort is a Divide and Conquer algorithm. It divides the input into two halves, calls itself for the two halves, and then merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, L, M, R) is a key process that assumes that arr[L..M] and arr[M + 1...R] are sorted and merges the two sorted subarrays into one.

Detailed explanation ( Input/output format, Notes, Images )
Constraints :
1 <= T <= 10
1 <= N <= 10^4
-10^9 <= data <= 10^9 and data != -1

Where data is the value associated with the node.

Time Limit: 1 sec
Sample Input 1:
3
1 -2 3 -1
9 9 -1
4 -1
Sample Output 1:
-2 1 3 -1
9 9 -1
4 -1
Explanation For Sample Output 1:
For every test case, the sorted list is printed, terminated by -1.
Sample Input 2:
2
1 1 1 -1
3 -3 -1
Sample Output 2:
1 1 1 -1
-3 3 -1
Full screen
Console