排序链表-力扣

对链表进行归并排序,两个链表的合并可以借用 合并两个有序链表

/**
 * 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){
            return head;
        }
        int len = 0;
        ListNode* cur = head;
        ListNode* dummyhead = new ListNode(0);
        dummyhead->next = head;
        while(cur != nullptr){
            cur = cur->next;
            len++;
        }
        for(int i = 1; i < len; i <<= 1){
            ListNode* prev = dummyhead, * curr = dummyhead->next;
            while(curr != nullptr){
                ListNode* l1 = curr;
                for(int j = 1; j < i && curr->next != nullptr; j++){
                    curr = curr->next;
                }
                ListNode* l2 = curr->next;
                curr->next = nullptr;
                curr = l2;
                ListNode* next = nullptr;
                for(int j = 1; j < i && curr != nullptr && curr->next != nullptr; j++){
                    curr = curr->next;
                }
                if(curr != nullptr){
                    next = curr->next;
                    curr->next = nullptr;
                }
                ListNode* merged = mergeTwoList(l1, l2);
                prev->next = merged;
                while(prev->next != nullptr){
                    prev = prev->next;
                }
                curr = next;
            }
        }
        return dummyhead->next;
    }

    ListNode* mergeTwoList(ListNode* list1, ListNode* list2){
        ListNode* dummyhead = new ListNode(0);
        ListNode* pre = dummyhead;
        while(list1 != nullptr && list2 != nullptr){
            if(list1->val < list2->val){
                pre->next = list1;
                list1 = list1->next;
            }else {
                pre->next = list2;
                list2 = list2->next;
            }
            pre = pre->next;
        }
        list1 == nullptr ? pre->next = list2 : pre->next = list1;
        return dummyhead->next;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值