首先我们使用一种便于理解的方法,将链表一分为二,然后归并排序,再合并两个有序链表。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if(head == nullptr || head->next == nullptr) 
            return head;
        ListNode* slow = head,*fast = head->next;
        while(fast && fast->next)
        {
            slow = slow->next;
            fast = fast->next->next;
        }
        //[slow]-->[---]->[---]
        //将链表一分为二
        fast = slow->next;
        slow->next = nullptr;
        return mergeTwoLists(sortList(head),sortList(fast));
    }
private:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode* dummy = new ListNode(-1);
        ListNode* p = dummy;

        while(l1 && l2)
        {
            if(l1->val < l2->val)
            {
                p->next = l1;
                l1 = l1->next;
            }else{
                p->next = l2;
                l2 = l2->next;
            }
            p = p->next;
        }
        if(l1) p->next = l1;
        if(l2) p->next = l2;

        return dummy->next;
    }
};

实现效率:

Runtime: 192 ms, faster than 6.59% of C++ online submissions for Sort List.
Memory Usage: 48.7 MB, less than 21.99% of C++ online submissions for Sort List.