Linked Lists Reversing and rewiring
309. Sort a Linked List of 0s, 1s and 2s
You are given head, the first node of a singly linked list. Every node holds the value 0, 1 or 2.
Rearrange the list so that all the 0s come first, then all the 1s, then all the 2s, and return the head of
the rearranged list.
The list keeps its length, and each value appears as many times as it did before. Any of the three values can be missing.
The examples write a list as its values from the head on, so head = [2,0,1] is the list 2 → 0 → 1. The
output shows the node you return the same way, as the list from that node on, and shows null as [].
Example 1
Input: head = [1, 2, 0, 1, 0, 2, 1]
[0,0,1,1,1,2,2]Explanation: The list holds two 0s, three 1s and two 2s. The two 0s come first, then the three 1s, then the two 2s.
Example 2
Input: head = [2, 0, 2, 0]
[0,0,2,2]Explanation: There are no 1s, so the two 2s come straight after the two 0s.
Example 3
Input: head = [2, 1, 1]
[1,1,2]Explanation: There are no 0s, so the list now starts at a node holding 1.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
0 ≤ number of nodes ≤ 105Node.valis0,1or2
Clarifying questions
What you would ask an interviewer before writing any code.