您的位置:首页 > 其它

leetcode - Merge k Sorted Lists

2014-10-25 18:06 211 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: