Search for a command to run...
Three chains, joined — no comparisons
Initialization
Three dummy heads front the 0, 1 and 2 chains, so appending never needs an "is this the first node?" check.
Three Chains
1function sortList(head) {2 if (head === null || head.next === null) return head;3 4 // Dummy heads for the three chains//length: 75 const zeroHead = new ListNode(-1);6 const oneHead = new ListNode(-1);7 const twoHead = new ListNode(-1);8 9 let zero = zeroHead, one = oneHead, two = twoHead;10 let temp = head;11 12 // Distribute every node into its chain13 while (temp !== null) {14 if (temp.data === 0) { zero.next = temp; zero = temp; }15 else if (temp.data === 1) { one.next = temp; one = temp; }16 else if (temp.data === 2) { two.next = temp; two = temp; }17 temp = temp.next;18 }19 20 // Join them, skipping the ones chain if it is empty21 zero.next = oneHead.next ? oneHead.next : twoHead.next;22 one.next = twoHead.next;23 two.next = null;24 25 return zeroHead.next;26}