Ctrl K

Sorting a List by Insertion

Medium
You are given the head of a singly linked list of integers. Sort the list in non-decreasing order and return its new head. Do it the way you sort a hand of cards: take the nodes one at a time from left to right and insert each into its place in the already sorted part. There is no need to create new nodes; rewiring the next links of the existing ones is enough.
Example 1
head=list_node([7, 3, 9, 3]) → [3, 3, 7, 9]

Both 3s move in front of 7, and 9 stays at the end.

Example 2
head=list_node([-2, 0, 6]) → [-2, 0, 6]

The list is already sorted, so each node simply stays at the tail.

Example 3
head=list_node([42]) → [42]
Constraints
  • 1 ≤ number of nodes ≤ 5000
  • -5000 ≤ Node.val ≤ 5000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSorting a Linked List MediumFrom Absolute Order to Actual Order MediumAdding Digit Lists MediumZero-Sum Triples MediumTriple Sum Nearest the Target Medium
loading Python…
Input
head=list_node([7, 3, 9, 3])
Expected
[3, 3, 7, 9]

Run checks the first 3 tests in your browser. Submit checks all 124 tests on the server, hidden ones included.