LeetCode148-排序链表-链表-归并排序-数据结构

LeetCode148-排序链表-链表-归并排序-数据结构,第1张

原题链接

Node:

贼拉麻烦,就是自己去模拟从底到顶的归并过程

代码如下:
/**
 * 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) {
        int n = 0;
        for(auto p = head; p; p = p -> next)    n ++;
        
        // i是每个小段的长度
        for(int i = 1; i < n; i *= 2){
            auto dummy = new ListNode(-1), cur = dummy;
            for(int j = 0; j <= n; j += i * 2){
                auto p = head, q = p;
                for(int k = 0; k < i && q; k ++)    q = q -> next;
                auto o = q;
                for(int k = 0; k < i && o; k ++)    o = o -> next;
                
                int l = 0, r = 0;
                while(l < i && r < i && p && q){
                    if(p -> val <= q -> val) cur = cur -> next = p, p = p -> next, l ++;
                    else    cur = cur -> next = q, q = q -> next, r ++;
                }
                while(l < i && p)   cur = cur -> next = p, p = p -> next, l ++;
                while(r < i && q)   cur = cur -> next = q, q = q -> next, r ++;
                head = o;
            }
            cur -> next = NULL;
            head = dummy -> next;
        }

        return head;
    }
};

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/723046.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-26
下一篇 2022-04-26

发表评论

登录后才能评论

评论列表(0条)

保存