合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
class CMP
{
public:
bool operator()(const ListNode* node1,const ListNode* node2)
{
return node1->val < node2->val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode* p;
vector<ListNode*> v;
for (int i = 0; i < lists.size(); ++i)
{
p = lists[i];
while (p){
v.push_back(p);
p = p->next;
}
}
if (v.size() == 0)
return nullptr;
sort(v.begin(), v.end(), CMP());
for (int i = 1; i < v.size(); ++i)
{
v[i - 1]->next = v[i];
}
v[v.size() - 1]->next = nullptr;
return v[0];
}
};