Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
struct CompareNode {
bool operator()(ListNode* const & p1, ListNode* const & p2) {
return p1->val > p2->val;
}
};
public:
ListNode *mergeKLists(std::vector<ListNode *> &lists) {
ListNode dummy(0);
ListNode* tail=&dummy;
std::priority_queue<ListNode*,std::vector<ListNode*>,CompareNode> queue;
for (std::vector<ListNode *>::iterator it = lists.begin(); it != lists.end(); ++it)
{
if (*it)
queue.push(*it);
}
while (!queue.empty())
{
tail->next=queue.top();
queue.pop();
tail=tail->next;
if (tail->next)
{
queue.push(tail->next);
}
}
return dummy.next;
}
};