Tutorialspoint
Problem
Solution
Submissions

Sort List

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to sort a linked list in O(n log n) time complexity and O(1) space complexity using merge sort algorithm. The linked list is represented using a singly linked list structure where each node contains an integer value and a pointer to the next node.

Example 1
  • Input: head = [4, 2, 1, 3]
  • Output: [1, 2, 3, 4]
  • Explanation: Apply merge sort on the linked list.
Example 2
  • Input: head = [-1, 5, 3, 4, 0]
  • Output: [-1, 0, 3, 4, 5]
  • Explanation: Apply merge sort algorithm to sort the linked list.
Constraints
  • The number of nodes in the list is in the range [0, 5 * 10^4]
  • -10^5 ≤ Node.val ≤ 10^5
  • Time Complexity: O(n log n)
  • Space Complexity: O(1) - constant extra space (not counting recursion stack)
  • Use merge sort algorithm
Linked ListAlgorithmsDeloitteEY
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use merge sort algorithm which naturally works well with linked lists
  • Find the middle of the linked list using slow and fast pointers
  • Split the linked list into two halves
  • Recursively sort both halves
  • Merge the two sorted halves back together
  • The merge operation should maintain sorted order

Steps to solve by this approach:

 Step 1: Check if the list has 0 or 1 elements (base case)
 Step 2: Find the middle of the linked list using slow and fast pointers
 Step 3: Split the linked list into two halves at the middle point
 Step 4: Recursively sort the left half
 Step 5: Recursively sort the right half
 Step 6: Merge the two sorted halves maintaining sorted order
 Step 7: Return the head of the merged sorted list

Submitted Code :