Linked Lists Reversing and rewiring
302. Sort List
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
Input: head = [4, -2, 9, 0, 7, -2, 3]
[-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
Input: head = [6, 1]
[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 = []
[]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.
Constraints
0 ≤ number of nodes ≤ 105-109 ≤ Node.val ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.