LeetCode 23. Merge k Sorted Lists

将所有起始不为空的链表的 头部存入优先队列,然后每次从优先队列里面取出值最小的, 并判断它的下一个节点是否为空,如果不为空,将下一个节点也存入优先队列。

class Solution
{
    struct cmp
    {
        bool operator ()(ListNode* &a, ListNode* &b)
        {
            return a->val > b->val;
        }
    };

public:
    ListNode* mergeKLists(vector<ListNode*>& lists)
    {
        priority_queue<ListNode*, vector<ListNode*>, cmp> que;

        for(int i=0; i<lists.size(); ++ i)
        {
            if(lists[i] != nullptr)
            {
                ListNode* f=lists[i];
                que.push(f);
                lists[i] = lists[i]->next;
            }
        }
        if(que.size() == 0)
            return nullptr;

        ListNode *arr = new ListNode(0);
        ListNode *bg = arr;

        while(!que.empty())
        {
            ListNode *f = que.top();
            que.pop();

            arr->val = f->val;
            if(f->next != nullptr)
                que.push(f->next);
            
            if(que.empty() == false)
            {
                arr->next = new ListNode(0);
                arr = arr->next;
            }
        }
        return bg;
    }
};
原文地址:https://www.cnblogs.com/aiterator/p/6525919.html