leetcode 23. 合并K个排序链表

本质上就是用优先队列来做,但是考虑的问题是 如何重载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;
    }
};
posted @ 2020-03-06 08:32  Draymonder  阅读(180)  评论(0编辑  收藏  举报