# LeetCode:Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

1、2合并，遍历2n个节点

12结果和3合并，遍历3n个节点

123结果和4合并，遍历4n个节点

123..k-1结果和k合并，遍历kn个节点

/**
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
if(lists.size() == 0)return NULL;
ListNode*res = lists[0];
for(int i = 1; i < lists.size(); i++)
res = merge2list(res, lists[i]);
return res;
}

{
ListNode node(0), *res = &node;
{
{
}
else
{
}
res = res->next;
}
return node.next;
}
};

1、3合并，合并结果放到1的位置

2、4合并，合并结果放到2的位置

/**
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/

class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
int n = lists.size();
if(n == 0)return NULL;
while(n >1)
{
int k = (n+1)/2;
for(int i = 0; i < n/2; i++)
lists[i] = merge2list(lists[i], lists[i + k]);
n = k;
}
return lists[0];
}

{
ListNode node(0), *res = &node;
{
{
}
else
{
}
res = res->next;
}
return node.next;
}
};

/**
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/

class Solution {
private:
struct cmp
{
bool operator ()(const ListNode *a, const ListNode *b)
{
return a->val > b->val;
}
};
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
int n = lists.size();
if(n == 0)return NULL;
ListNode node(0), *res = &node;
priority_queue<ListNode*, vector<ListNode*>, cmp> que;
for(int i = 0; i < n; i++)
if(lists[i])
que.push(lists[i]);
while(!que.empty())
{
ListNode * p = que.top();
que.pop();
res->next = p;
res = p;

if(p->next)
que.push(p->next);
}
return node.next;
}
};

【版权声明】转载请注明出处http://www.cnblogs.com/TenosDoIt/p/3673188.html

posted @ 2014-04-18 14:33  tenos  阅读(...)  评论(...编辑  收藏