AlgoFrames

Sort a linked list

Standard · Write code · about 20 min

Sort a singly linked list ascending in O(n log n) time and return the new head. Relink the existing nodes.

Find the middle with a slow and a fast pointer, cut the list there, sort both halves recursively and merge them by relinking.

Example 1

Input:

[[4,2,1,3]]

Output:

[1,2,3,4]

Example 2

Input:

[[-1,5,3,4,0]]

Output:

[-1,0,3,4,5]

Constraints

  • 0 ≤ number of nodes ≤ 10,000
  • -100,000 ≤ Node.val ≤ 100,000

Learn the idea first: Merge sort, a visual lesson.

More Merge sort problems