148. Sort List
Problem
Sort a linked list in ascending order and return its head.
Example: 4→2→1→3 → 1→2→3→4
Constraints: up to 5·10⁴ nodes. Follow-up: O(n log n) time with O(1) memory.
Merge sort is natural for lists: split at the middle (fast/slow), sort halves recursively, merge (21).
Complexity: O(n log n) time, O(log n) recursion.
class Solution:
def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
slow, fast = head, head.next
while fast and fast.next:
slow, fast = slow.next, fast.next.next
mid, slow.next = slow.next, None
a, b = self.sortList(head), self.sortList(mid)
dummy = tail = ListNode()
while a and 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 or b
return dummy.next
assert list_vals(Solution().sortList(make_list([4, 2, 1, 3]))) == [1, 2, 3, 4]
assert list_vals(Solution().sortList(make_list([-1, 5, 3, 4, 0]))) == [-1, 0, 3, 4, 5]
class Solution {
public ListNode sortList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode slow = head, fast = head.next;
while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; }
ListNode mid = slow.next;
slow.next = null;
ListNode a = sortList(head), b = sortList(mid), dummy = new ListNode(), tail = dummy;
while (a != null && b != null) {
if (a.val <= b.val) { tail.next = a; a = a.next; } else { tail.next = b; b = b.next; }
tail = tail.next;
}
tail.next = a != null ? a : b;
return dummy.next;
}
}
func sortList(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
slow, fast := head, head.Next
for fast != nil && fast.Next != nil {
slow, fast = slow.Next, fast.Next.Next
}
mid := slow.Next
slow.Next = nil // split, sort both halves, merge
a, b := sortList(head), sortList(mid)
dummy := &ListNode{}
tail := dummy
for a != nil && b != nil {
if a.Val <= b.Val {
tail.Next, a = a, a.Next
} else {
tail.Next, b = b, b.Next
}
tail = tail.Next
}
if a != nil {
tail.Next = a
} else {
tail.Next = b
}
return dummy.Next
}