Problem
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Code
class comp
{
public:
bool operator()(ListNode *l1,ListNode *l2)
{
return (l1->val > l2->val);
}
};
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
// Note: The Solution object is instantiated only once and is reused by each test case.
priority_queue<ListNode *,vector<ListNode *>,comp> Q;
vector<ListNode *>::const_iterator it = lists.begin();
for(;it != lists.end();++it){
ListNode *phead = *it;
if(phead != 0)
Q.push(*it);
}
if(Q.empty())
return 0;
ListNode *head = Q.top();
Q.pop();
if(head->next)
Q.push(head->next);
ListNode *node = head;
while(!Q.empty()){
ListNode *tmp = Q.top();
Q.pop();
node->next = tmp;
if(tmp->next)
Q.push(tmp->next);
node = tmp;
}
node->next = 0;
return head;
}
};
No comments:
Post a Comment