题解 | #合并k个已排序的链表#

合并k个已排序的链表

https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6

/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 *  ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
struct LISTNODECOMPARE {
    bool operator()(ListNode* a, ListNode* b) {
        return a->val >= b->val;
    }
};

class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param lists ListNode类vector
     * @return ListNode类
     */
    ListNode *mergeKLists(vector<ListNode *> &lists)
    {
        priority_queue<ListNode *, vector<ListNode *>, LISTNODECOMPARE> pq;
        for (auto &l : lists)
        {
            if (l != nullptr)
                pq.push(l);
        }
        ListNode *head = nullptr;
        ListNode *tail = nullptr;
        while (!pq.empty())
        {
            auto a = pq.top();
            ListNode *b = a->next;
            a->next = nullptr;
            pq.pop();
            if (!head)
            {
                head = a;
                tail = head;
            }
            else
            {
                tail->next = a;
                tail = tail->next;
            }
            if (b)
                pq.push(b);
        }
        return head;
    }
};

对每个头节点进行堆排序

全部评论

相关推荐

02-22 21:16
已编辑
门头沟学院 运营
牛客928043833号:离了你谁还拿我当个宝
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务