本质上就是用优先队列来做,但是考虑的问题是 如何重载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; } };
来源:https://www.cnblogs.com/Draymonder/p/12424682.html