此题利用分治法,将给定的K个链表分成两份,对每一份继续划分,直到最后连个链表进行合并
代码
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
ListNode *newHead = NULL;
int len = lists.size();
if(len==0)
return newHead;
return helper(lists, 0, len-1);
}
ListNode * helper(vector<ListNode*> &lists, int l, int r)
{
if(l<r)
{
int m = (l+r)/2;
return mergeTwoList(helper(lists, l, m), helper(lists, m+1, r));
}
return lists[l];
}
ListNode * mergeTwoList(ListNode *L1, ListNode *L2)
{
ListNode *newHead = new ListNode(0);
ListNode *p = newHead;
ListNode *p1, *p2;
p1 = L1;
p2 = L2;
while(p1!=NULL&&p2!=NULL)
{
if(p1->val>=p2->val)
{
p->next = p2;
p2 = p2->next;
}
else
{
p->next = p1;
p1 = p1->next;
}
p = p->next;
}
if(p1!=NULL)
p->next = p1;
if(p2!=NULL)
p->next = p2;
return newHead->next;
}
};