随笔 - 165,  文章 - 0,  评论 - 4,  阅读 - 18023

题目:

时间复杂度: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   孜孜不倦fly  阅读(10)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示