首页 > 编程语言 > 详细

leetcode 23. 合并K个排序链表

时间:2020-03-06 09:52:58      阅读:51      评论:0      收藏:0      [点我收藏+]

本质上就是用优先队列来做,但是考虑的问题是 如何重载cmp比较函数

参考网络上的写法

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        auto cmp = [](ListNode* &a, ListNode* &b) {
            return a->val > b->val;
        };
        priority_queue<ListNode*, vector<ListNode*>, decltype(cmp)> que(cmp);

        for (auto node : lists) 
            if (node)
                que.push(node);

        ListNode *first = new ListNode(-1);
        ListNode *res = first;
        
        while (!que.empty()) {
            ListNode *a = que.top();
            que.pop();
            first->next = a;
            first = first->next;
            if (a->next) 
                que.push(a->next);
        }
        return res->next;
    }
};

leetcode 23. 合并K个排序链表

原文:https://www.cnblogs.com/Draymonder/p/12424682.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!