力扣练习第十三天——合并K个排序链表
题目大致如下:
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:
[
1->4->5,
1->3->4,
2->6
]
输出: 1->1->2->3->4->4->5->6
链接来源于LeetCode:https://leetcode-cn.com/problems/merge-k-sorted-lists/submissions/
大致思路:
采用了昨天的思路,主要是两两组合,进行两个链表的合并。然后得到K个链表的组合。
代码大致如下:
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.size() == 0) return NULL;
if(lists.size() == 1) return lists[0];
ListNode* p = lists[0];
for(int i=1; i<lists.size(); i++) {
p = mergeTwoLists(p, lists[i]);
}
return p;
}
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(!l1) return l2;
if(!l2) return l1;
ListNode head(0);
ListNode* h = &head;
while(l1 && l2) {
if(l1->val <= l2->val) {
h->next = l1;
l1 = l1->next;
} else {
h->next = l2;
l2 = l2->next;
}
h = h->next;
}
if(l1 == NULL) h->next = l2;
else h->next = l1;
return head.next;
}
};
结果大致如下: