和Leetcode 21. 合并两个有序链表类似
用堆排序每次选一个最小的,然后把这个最小的下一个元素加入堆中(可用priority_queue)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
struct cmp {
bool operator()(ListNode *a, ListNode *b) {
return a->val > b->val;
}
};
ListNode * mergeKLists(vector<ListNode*>& lists) {
ListNode *p = NULL, *q = NULL;
priority_queue<ListNode*, vector<ListNode*>, cmp> que;
for (auto x : lists)
if (x) que.push(x);
if (que.empty()) return p;
p = q = que.top(); que.pop();
if (p->next) que.push(p->next);
while (!que.empty()) {
auto x = que.top(); que.pop();
q = q->next = x;
if (x->next) que.push(x->next);
}
return p;
}
};