Problem
Sort a singly linked list using insertion sort and return its new head. Repeatedly take the next unprocessed node and insert it at a suitable position in the already sorted chain. Move nodes into that chain in place.
ListNode* insertionSortList(ListNode* head);
ListNode has val and next. Example brackets display linked nodes, not an array input or return. No additional equal-key identity ordering is specified.
Examples
Input chain: [6,2,5,1]
Output chain: [1,2,5,6]
Input chain: [0,-3,2,-3]
Output chain: [-3,-3,0,2]
Constraints
-
There are between 1 and 5000 nodes.
-
Values lie between -5000 and 5000, inclusive.
-
Use insertion sort, rather than substituting a different sorting algorithm.