思路
这是two-ways-merge的一般情况,考虑使用一个小顶堆维护排序当前集合最小的元素所在节点的地址,实现上,涉及到自定义存储结构和比较规则,由于弹出最小元素挂到新链表后,需要找到链表的下一个节点,所以需要存储节点所在的链表下标
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
struct cmp{
bool operator() (pair<ListNode*,int >& lhs , pair<ListNode*,int >& rhs){
if (lhs.first->val > rhs.first->val ){
return true;
}
return false;
}
};
priority_queue<pair<ListNode*,int >,vector<pair<ListNode*,int >>,cmp> p;
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
//insert into heap;
for (int i = 0 ; i < lists.size() ; ++i){
if(lists[i]!=nullptr){
p.push(make_pair(lists[i],i));
}
}
ListNode* newlist = new ListNode(-1);
ListNode* cur = newlist;
while( !p.empty() ){
int cur_list = p.top().second;
cur->next = p.top().first;
//cout << cur->next->val;
p.pop();
if (cur->next->next != nullptr){
p.push(make_pair(cur->next->next,cur_list));
}
cur = cur->next;
}
cur->next = nullptr;
return newlist->next;
}
};