题解 | #合并k个已排序的链表#
合并k个已排序的链表
http://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
优先队列,将全部非空的节点全部入队,然后每次选出最小的后,将选出的链表头指针往后移动一个位置,再次入队,如此反复
/**
* 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* x, ListNode* y){
return x->val > y->val;
};
priority_queue<ListNode*, vector<ListNode*>, decltype(cmp)> q(cmp);
for(ListNode* l : lists){
if(l) q.push(l);
}
ListNode* dummy = new ListNode(0);
ListNode* cur = dummy;
while(!q.empty()){
ListNode* tmp = q.top();
q.pop();
cur->next = tmp;
cur = cur->next;
tmp = tmp->next;
if(tmp) q.push(tmp);
}
return dummy->next;
}
};