题目
题目链接
题目描述
代码实现
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param lists ListNode类vector
* @return ListNode类
*/
ListNode* mergeKLists(vector<ListNode*>& lists) {
// write code here
return DivideList(lists, 0, lists.size() - 1);
}
ListNode* DivideList(vector<ListNode*>& lists, int left, int right) {
if (left > right)
return nullptr;
//中间只有一个链表的情况
if (left == right)
return lists[right];
//从中间分为两段,在将两段合并好的链表再合并
int mid = (left + right) / 2;
return MergeList(DivideList(lists, left, mid), DivideList(lists, mid + 1,right));
}
ListNode* MergeList(ListNode* head1, ListNode* head2) {
if (head1 == nullptr)
return head2;
if (head2 == nullptr)
return head1;
ListNode* phead = new ListNode(0);
ListNode* cur = phead;
while (head1 && head2) {
if (head1->val <= head2->val) {
cur->next = head1;
head1 = head1->next;
} else {
cur->next = head2;
head2 = head2->next;
}
cur = cur->next;
}
cur->next = head1 == nullptr ? head2 : head1;
return phead->next;
}
};
思路分析
首先这里使用到了归并的思想,即将大问题转换成为一个个小问题。这里建议可以看看下边我的这篇博文
1、首先将多个链表分解成为两个链表一组的小问题,然后在使用合并两个有序链表的思路。
合并两个有序链表参考我的这篇博文
2、将多个链表分成两两一组的时候有两种情况,一、中间只有一个链表的情况。二、从中间分为两段,在将两段合并好的链表再合并