题目描述:
leetcode23
思路:
代码实现:
/**
* 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) {
if(lists.empty()) return NULL;
int n = lists.size();
while(n > 1){
int k = (n + 1)/2;
for(int i = 0; i < n / 2; i++){//分别合并n/2次
lists[i] = helper(lists[i],lists[i+k]);
}
n = k;//继续下一次合并
}
return lists[0];
}
ListNode* helper(ListNode* l1, ListNode* l2){
ListNode* dummy = new ListNode(-1), *cur = dummy;
while(l1 && l2){
if(l1->val < l2->val){
cur -> next = l1;
l1 = l1->next;
}else{
cur -> next = l2;
l2=l2->next;
}
cur = cur->next;
}
if(l1) cur ->next = l1;
if(l2) cur->next = l2;
return dummy->next;
}
};
class Compare{
public://【注意这里必须写成public】
bool operator()(ListNode* l1, ListNode*l2){
return l1->val > l2->val;
}
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
priority_queue<ListNode*, vector<ListNode*>,Compare> q;
for(auto i : lists){
if(i) q.push(i);
}
ListNode* dummy = new ListNode(-1), *cur = dummy;
while(!q.empty()){
auto t = q.top();
q.pop();
cur->next = t;
cur = cur->next;
if(cur->next) q.push(cur->next);
}
return dummy->next;
}
};
参考:https://blog.csdn.net/zlasd/article/details/52605601、
参考:https://www.cnblogs.com/grandyang/p/4606710.html