VOOZH about

URL: https://www.geeksforgeeks.org/dsa/merge-sort-for-linked-list/

⇱ Merge Sort for Linked Lists - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Merge Sort for Linked Lists

Last Updated : 26 Aug, 2025

Given a singly linked list, we need to sort the linked list in non-decreasing order using merge sort.

Examples:

Input:

👁 blobid2_1756114643


Output:

👁 blobid3_1756114660

Explanation: After sorting the given linked list , resultant will be 2 -> 5 -> 8 -> 9.

Input:

👁 blobid0_1756114630


Output:

👁 blobid1_1756114636

Explanation: After sorting the given linked list, the resultant matrix will be 10 -> 20 -> 30 -> 40 -> 50 ->60 ->NULL.


Approach:

The prerequisite for this problem is Merge Sort. Here we have to maintain a MergeSort function that sorts the list in three steps:

  1. Split the List into Two Halves: Use two pointers, fast and slow, starting at the head. Move fast two steps and slow one step. When fast reaches the end, slow is at the midpoint. Split the list into two halves: the first half from head to just before slow, and the second from slow->next to the end. Set slow->next to NULL.
  2. Apply MergeSort Recursively: Recursively call MergeSort() on both halves. The base case is when the list is empty (head == NULL) or has one node (head->next == NULL), in which case return the list as is.
  3. Merge the Two Sorted Halves: After sorting both halves, call merge() to merge them by comparing nodes and linking accordingly. Append any remaining nodes from the exhausted half. Finally, returns the new head of the sorted list.

Output
2 -> 5 -> 8 -> 9 

Time Complexity: O(n*log(n))
Auxiliary Space: O(logn)

Comment