【leetcode】插入排序一个链表

ListNode* insertionSortList(ListNode* head)
{
    ListNode * new_head = new ListNode(0);
    new_head->next = head;
    ListNode* pre = new_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;//要插入需要找到正确位置的前一个位置
            }

           //穿针引线改变指针的指向
            ListNode* temp = pre->next;
            pre->next = cur->next;
            cur->next = cur->next->next;
            pre->next->next = temp;

            pre = new_head;

        }
        else
        {
            cur = cur->next;
        }

    }
    ListNode*res = new_head->next;
    delete new_head;
    return res;

}

你可能感兴趣的:(数据结构)