23. Merge k Sorted Lists
problem description
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6algorithm thought
code
/**
* 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()(const ListNode* l1,ListNode* l2){
return l1->val>l2->val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.size()==0)
return NULL;
priority_queue<ListNode*,vector<ListNode*>,cmp> pro;
for(auto list:lists){
if(list)
pro.push(list);
}
ListNode* res=new ListNode(-1);
ListNode* tmp=res;
while(!pro.empty()){
tmp->next=pro.top();
pro.pop();
tmp=tmp->next;
if(tmp->next)
pro.push(tmp->next);
}
return res->next;
}
};algorithm analysis
Last updated