oneby7

Linked Lists Reversing and rewiring

302. Sort List

Medium

You are given head, the first node of a singly linked list. Sort the list in non-decreasing order and return the head of the sorted list.

Non-decreasing order means each value is at least the one before it, so equal values sit next to each other. The sorted list keeps every node, duplicates included. The list can be empty, and an empty list is a null head; then return null.

The examples write a list as its values from the head on, so head = [4,1,6] is the list 4 → 1 → 6. The output shows the list you return the same way, and an empty list as [].

Example 1

head
4-2907-23
output
-2-203479

Input: head = [4, -2, 9, 0, 7, -2, 3]

Output: [-2,-2,0,3,4,7,9]

Explanation: All seven nodes are in the answer, smallest first. The value -2 appears twice, and both nodes are kept, next to each other.

Example 2

61
head
16
output

Input: head = [6, 1]

Output: [1,6]

Explanation: The two nodes are out of order, so they swap places, and the node holding 1 becomes the head.

Example 3

Input: head = []

Output: []

Explanation: The list is empty, so there is nothing to sort, and the answer is null.

Check your understanding

Work out the answer for this input before you write any code.

head = [3, 1, 2, 1]

Constraints

  • 0 ≤ number of nodes ≤ 105
  • -109 ≤ Node.val ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.