合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入: [ 1->4->5,
1->3->4,
2->6 ]
输出: 1->1->2->3->4->4->5->6
mergeTwoLists()合并两个列表,把vector循环两两相连接。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode *a,ListNode *b){
ListNode * head = new ListNode(0);
ListNode * ans = head;
ListNode *l1 = a,*l2 = b;
while(l1 && l2)
{
if(l1->val > l2->val)
{
ans->next = l2;
l2 = l2->next;
}else{
ans->next = l1;
l1 = l1->next;
}
ans = ans->next;
}
ans->next = l1?l1:l2;//接上剩下的部分
return head->next;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode * res = NULL;
for(int i=0;i<lists.size();i++)
{
res = mergeTwoLists(res,lists[i]);
}
return res;
}
};