标签:cto sts type def ini const nullptr ret auto
给定多个有序链表,按有小到大的方式合并成一个链表
关键词:优先队列,链表
// 最基本的两条链表合并
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        auto cmp = [](const ListNode* a, const ListNode* b) {
            return a->val > b->val;
        };
        std::priority_queue<ListNode*, std::vector<ListNode*>, decltype(cmp)> pq(cmp);
        if(l1 != nullptr) pq.push(l1);
        if(l2 != nullptr) pq.push(l2);
        ListNode head(0);
        ListNode* p = &head;
        while(!pq.empty()) {
            p->next = pq.top();
            p = p->next;
            pq.pop();
            if(p->next != nullptr) pq.push(p->next);
        }
        return head.next;
    }
};
因为每条链有序
借助优先队列,每次将每条链表的比较节点放入队列中,然后比较选择出一条链,将当前节点加入合并的链表中,然后将该节点的下一个节点放入队列中比较(如果存在)。
标签:cto sts type def ini const nullptr ret auto
原文地址:https://www.cnblogs.com/codemeta-2020/p/12813332.html