Sort List

Top-down merge sort on a linked list — slow/fast split, recurse, merge two sorted lists.

Medium
Time O(n log n) Space O(log n) recursion
LeetCode
4 min read
linked-list merge-sort divide-and-conquer

Problem#

Sort a singly linked list in ascending order.

Examples#

  • [4,2,1,3][1,2,3,4].
  • [-1,5,3,4,0][-1,0,3,4,5].

Constraints#

  • 0 <= nodes <= 5 * 10^4.

Approach#

Top-down merge sort. Find the middle with slow/fast pointers, split, sort each half recursively, merge.

Solution#

Sort List
struct ListNode { int val; ListNode* next; };
class Solution {
ListNode* merge(ListNode* a, ListNode* b) {
ListNode dummy(0), *tail = &dummy;
dummy.next = nullptr;
while (a && b) {
if (a->val <= b->val) { tail->next = a; a = a->next; }
else { tail->next = b; b = b->next; }
tail = tail->next;
}
tail->next = a ? a : b;
return dummy.next;
}
public:
ListNode* sortList(ListNode* head) {
if (!head || !head->next) return head;
ListNode *slow = head, *fast = head->next;
while (fast && fast->next) { slow = slow->next; fast = fast->next->next; }
ListNode* mid = slow->next;
slow->next = nullptr;
return merge(sortList(head), sortList(mid));
}
};

Editorial#

Linked lists have O(1) splice and merge but no random access, making merge sort ideal — it’s stable, doesn’t rely on indexing, and matches list semantics. The fast = head->next start ensures the split lands at the correct midpoint for even-length lists.

Complexity#

  • Time: O(n log n).
  • Space: O(log n) recursion stack.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.