AlgoFrames

Insertion sort on a linked list

Challenge · Write code · about 20 min

Sort a singly linked list ascending with insertion sort and return the new head. Reuse the existing nodes: relink them instead of creating new ones.

A list has no index, so you cannot shift values left. Walk from the front of the sorted part to find each node's place instead.

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 ≤ 1,000
  • -5,000 ≤ Node.val ≤ 5,000

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

More Insertion sort problems