题目链接:
https://leetcode-cn.com/problems/merge-k-sorted-lists/
题目描述:
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
题解:
归并法,分而治之的思想。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
//链表两两合并
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *L = new ListNode(-1);
ListNode *p = L;
while(l1 != nullptr && l2 != nullptr)
{
if(l1->val < l2->val)
{
p->next = l1;
l1 = l1->next;
}else
{
p->next = l2;
l2 = l2->next;
}
p = p->next;
}
p->next = l1 == nullptr ? l2 :l1;
return L->next;
}
ListNode* merge(vector<ListNode*>& lists, int left, int right)
{
if(left == right)
return lists[left];
int mid = left + (right - left) / 2;
ListNode* l1 = merge(lists, left, mid);
ListNode* l2 = merge(lists, mid + 1, right);
return mergeTwoLists(l1, l2);
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.size() == 0)
return nullptr;
return merge(lists, 0, lists.size() - 1);
}
};