Sort the Nodes of a Linked List
Implement sortLinkedList
Given the
head of a singly linked list, sort it in non-decreasing order and return the sorted list's head.
Because a linked list can't be randomly indexed the way an array can, most in-place sorting algorithms don't translate directly. Merge sortMerge Sort on a Linked ListA divide-and-conquer sort: split the list into two halves (using slow/fast pointers to find an even split point), recursively sort each half, then merge the two sorted halves back together. Unlike merge sort on an array, no auxiliary array is ever needed — splitting only cuts a link, and merging only re-links existing nodes. is the exception — it only ever needs sequential access, both to split the list (find a midpoint, cut the link) and to merge two already-sorted halves (walk both with two pointers, re-linking as you go, exactly like merging two sorted lists). That makes it a natural fit for a linked list, running in O(n log n) time using only O(log n) extra space for the recursion.
Example 1:
Input: head = [4,2,1,3]
Output: [1,2,3,4]
Example 2:
Input: head = []
Output: []
Example 3:
Input: head = [1]
Output: [1]
+ 5 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ number of nodes in head ≤ 500 - ●
-10⁵ ≤ node value ≤ 10⁵ - ●
The list is not guaranteed to be sorted
head =
[4, 2, 1, 3]