被这个题困扰很久,最后发现比较好的解法是做辅助链表来存已经有序的排列,而不是在原来的链表上直接进行排序。
ListNode* insertionSortList(ListNode* head)
{
if (head == nullptr || head->next == nullptr)
return head;
ListNode* dummy = new ListNode(INT_MIN);
ListNode* ptr = head;//ptr指向要被移动的元素
while (ptr)
{
ListNode* pNext = ptr->next;
head = dummy;
while (head->next && head->next->val < ptr->val)
head = head->next;
ptr->next = head->next;
head->next = ptr;
ptr = pNext;
}
return dummy->next;
}