【leetcode】插入排序一个链表

来源:互联网 发布:安卓模拟器 for mac 编辑:程序博客网 时间:2024/05/21 09:21
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;}
0 0