sort-list.sh — zsh
linked-listmerge-sortdivide-and-conquer

Given the head of a singly linked list, return the head of the list sorted in ascending order. The input is a real ListNode chain built by the judge from a flat JSON array such as [4, 2, 1, 3], and whatever linked list you return is serialized back to the same flat-array form for grading.

You may solve this by collecting values into an array and rebuilding the list, but interviewers usually want the linked-list merge-sort solution because it keeps the sorting work on the nodes themselves.

Input / output

  • Input: head: ListNode
  • Output: ListNode — the head of the sorted linked list

Examples

  1. head = [4, 2, 1, 3] returns [1, 2, 3, 4].
  2. head = [-1, 5, 3, 4, 0] returns [-1, 0, 3, 4, 5].
  3. head = [] returns [].

Constraints

  • 0 <= number of nodes <= 50,000
  • -100,000 <= node value <= 100,000
  • The list may contain duplicate values.

Follow-up Can you sort the list in O(n log n) time without converting it to an array first, and explain why merge sort is a natural fit for linked lists?

Examples
Example 1
Input: head = [4,2,1,3]
Output: [1,2,3,4]
Example 2
Input: head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]
Example 3 (empty list)
Input: head = []
Output: []