Sort a linked list using insertion sort.
//
// start: Sort list using insert sort
ListNode *findInsertPos(ListNode *head, int x)
{
ListNode *pos = NULL;
for(ListNode *current = head; current != NULL && current->val <= x; pos = current, current = current->next); // 从大到小
return pos;
}
ListNode *insertionSortList(ListNode *head)
{
ListNode result(INT_MIN); // 以后链表均初始建立一个带值的头,最后跳过它,这里初值赋MIN
for(ListNode *current = head; current != NULL)
{
auto pos = findInsertPos(&result, current->val); // current插在pos处
ListNode *tmp = current->next;
current->next = pos->next;
pos->next = current;
current = tmp;
}
return result.next;
}
// end
//