思路:因为链表的特性,插入排序无法从当前元素往前遍历,所以这里直接从头开始查找插入位置,分头部插入、中间插入和尾部插入;
ListNode *insertionSortList(ListNode *head)
{
if (!head || !(head->next))
return head;
ListNode *cur = head->next;
head->next = nullptr;
ListNode *next = nullptr;
while (cur)
{
ListNode *dest = head;
ListNode *pre = nullptr;
//找到插入位置
while (dest && dest->val < cur->val)
{
pre = dest;
dest = dest->next;
}
//暂时存储cur的下一个节点,待cur插入后赋值给cur
next = cur->next;
if (!pre) //头部插入
{
cur->next = head;
head = cur;
}
else if (dest) //中间插入
{
ListNode *temp = pre->next;
pre->next = cur;
cur->next = temp;
}
else //尾部插入
{
pre->next = cur;
cur->next = nullptr;
}
cur = next;
}
return head;
}