题目:

时间复杂度:O(nlogn),空间复杂度:O(1)

struct ListNode{
    int val;
    ListNode* next;
    ListNode(): val(0), next(nullptr) {}
    ListNode(int _val): val(_val), next(nullptr) {}
    ListNode(int _val, ListNode* _next): val(_val), next(_next) {}
};

class Solution {
public:
    ListNode* sortList(ListNode* head) {
        return mergesort(head);
    }
    //归并排序链表
    ListNode* mergesort(ListNode* head){
        if(!head || !head->next) return head;
        ListNode* end1 = getmid(head);
        ListNode* rightlist = mergesort(end1->next);
        end1->next = nullptr;       //在对左子链表进行排序前要断开和右子链表的链接
        ListNode* leftlist = mergesort(head);
        return mergetwo(leftlist, rightlist);

    }
    //合并两个有序链表
    ListNode* mergetwo(ListNode* l1, ListNode* l2){
        ListNode* dummy = new ListNode(0);
        ListNode* cur = dummy;
        while(l1&&l2){
            if(l1->val<l2->val){
                cur->next = l1;
                l1 = l1->next;
            }else{
                cur->next = l2;
                l2 = l2->next;
            }
            cur = cur->next;
        }
        cur->next = l1 ? l1 : l2;
        return dummy->next;
    }
    //取得中间节点
    ListNode* getmid(ListNode* head){
        ListNode* slow = head;
        ListNode* fast = head;
        while(fast->next&&fast->next->next){
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }

};
posted on 2024-03-11 21:24  孜孜不倦fly  阅读(8)  评论(0编辑  收藏  举报