23 合并多个排序列表 C++l思路

分治的思路很好想 也比较好理解

    ListNode* mergelist(ListNode *a, ListNode *b){
        if(!a)return b;
        if(!b)return a;
        if(a -> val < b -> val){
            a -> next = mergelist(a -> next, b);
            return a;
        }
        else{
            b -> next = mergelist(a, b -> next);
            return b;
        }
    }
    ListNode* merge(vector &lists, int l, int r){
        if(l == r)return lists[l];
        int mid = (l + r) / 2;
        return mergelist(merge(lists, l, mid), merge(lists, mid + 1, r));
    }
    ListNode* mergeKLists(vector& lists) {
        if(lists.size() == 0)return NULL;
        return merge(lists, 0, lists.size() - 1);
    }

官方给的优先队列思路很精妙 值得学习 

首先把每个链表的第一个节点入列, 优先队列通过小根堆调整,每次都是最小的节点在队头

每次把队头节点出列接在目标链表后面,然后把出列节点的下一个节点入列,再调整大小


  struct Status {
        int val;
        ListNode *ptr;
        bool operator < (const Status &rhs) const {
            return val > rhs.val;
        }
    };

    priority_queue  q;

    ListNode* mergeKLists(vector& lists) {
        for (auto node: lists) {
            if (node) q.push({node->val, node});
        }
        ListNode head, *tail = &head;
        while (!q.empty()) {
            auto f = q.top(); q.pop();
            tail->next = f.ptr; 
            tail = tail->next;
            if (f.ptr->next) q.push({f.ptr->next->val, f.ptr->next});
        }
        return head.next;
    }


 

你可能感兴趣的:(c++学习)