对链表进行插入排序,比对数组排序麻烦一点。

Insertion Sort List_链表Insertion Sort List_链表_02

ListNode *insertSortList(ListNode *head)
{
ListNode dummy(-1);
for (ListNode *cur = head; cur != nullptr;)
{
//将当前结点插入到此结点之后
auto Pos = findPos(&dummy, cur->val);
//保存当前结点的下一个结点
ListNode *temp = cur->next;
//插入
cur->next = Pos->next;
Pos->next = cur;
//继续下一个结点
cur = temp;
}
}

ListNode *findPos(ListNode *head, int val)
{
ListNode *pre = nullptr;
for (ListNode *cur = head; cur != nullptr&&cur->val <= val; pre = cur, cur = cur->next);

return pre;
}

View Code