Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
将k个有序链表合并成一个有序链表。
思路,之前做过两个有序链表的合并操作,对于k个链表,我们最先想到的就是能不能转化为我们熟悉的两个链表的合并,可以我们先将k个链表分为两部分,先对这两部分完成链表的有序合并操作,再对合并得到的两个链表进行合并,这是一个递归性质的描述,采用递归很容易实现这个程序,和数组的归并排序很类似。
Accepted Solution:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists)
{
return mergeSort(lists, 0, lists.size() - 1);
}
ListNode *mergeSort(vector<ListNode *> &lists, int begin, int end)
{
if (begin>end)
return NULL;
if (begin == end)
return lists[begin];
int mid = (begin + end) / 2;
ListNode *head1 = mergeSort(lists, begin, mid);
ListNode *head2 = mergeSort(lists, mid + 1, end);
ListNode *dummyHead = new ListNode(0),*p = dummyHead;
while (head1 != NULL&&head2 != NULL)
{
if (head1->val<head2->val)
{
p->next = head1;
head1 = head1->next;
p = p->next;
}
else
{
p->next = head2;
head2 = head2->next;
p = p->next;
}
}
if (head1 != NULL)
p->next = head1;
if (head2 != NULL)
p->next = head2;
p = dummyHead->next;
delete dummyHead;
return p;
}
};