Sort a linked list using insertion sort.
ListNode* insertionSortList(ListNode* head) {
if (!head||!head->next) return head;
ListNode preHead(0),*pre=&preHead;
preHead.next=head;
ListNode* cur = head;
while (cur) {
if (cur -> next && cur -> next -> val < cur -> val) {
while (pre -> next && pre -> next -> val < cur -> next -> val)
pre = pre -> next;
/* Insert cur -> next after pre.*/
ListNode* temp = pre -> next;
pre -> next = cur -> next;
cur -> next = cur -> next -> next;
pre -> next -> next = temp;
// Move pre back
pre = &preHead;
}
else cur = cur -> next;
}
return preHead.next;
}