Topic links: https://leetcode-cn.com/problems/merge-k-sorted-lists/
Title Description
K merge sort list, return the list sorted combined. Please complexity analysis and description of the algorithm.
Example:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
Thinking
1 one by one twenty-two merging sorted linked list
The combined list of the k problem into two lists combined k-1 times. Here are 21 merge two ordered list of topics.
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode *head = nullptr;
if(lists.empty()) return head;
for (auto list:lists) {
head = mergeTwoLists(head, list);
}
return head;
}
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1 == nullptr) return l2;
if(l2 == nullptr) return l1;
if(l1->val < l2->val){
l1->next = mergeTwoLists(l1->next, l2);
return l1;
}else{
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};