【leetcode】【剑指offer Ⅱ】077. 链表排序

问题描述:

  • 给定链表的头结点 head,请将其按升序排列并返回排序后的链表。

核心思路:

  • 归并排序链表版本。

代码实现:

class Solution
{
private:
    ListNode* merge_list(ListNode* left, ListNode* right)
    {
        if(!right)
            return left;
        ListNode* dummy = new ListNode(-1);
        ListNode* cur = dummy;
        while(left && right)
        {
            if(left->val < right->val)
                cur->next = left, left = left->next, cur = cur->next;
            else
                cur->next = right, right = right->next, cur = cur->next;
        }
        cur->next = left ? left : right ? right : nullptr;
        cur = dummy->next;
        delete dummy;
        return cur;
    }
public:
    ListNode* sortList(ListNode* head)
    {
        if(!head || !head->next)
            return head;
        ListNode* dummy = new ListNode(-1, head);
        ListNode* slow = dummy;
        ListNode* fast = dummy;
        while(fast && fast->next)
            slow = slow->next, fast = fast->next->next;
        ListNode* tmp = slow->next;
        slow->next = nullptr;
        slow = sortList(dummy->next);// 左边头
        fast = sortList(tmp);// 右边头
        tmp = merge_list(slow, fast);
        delete dummy;
        return tmp;
    }
};

你可能感兴趣的:(#,剑指,offer,Ⅱ,leetcode)