/**
* 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) {
if(lists.empty()) return 0;
size_t i=0;
for(;i!=lists.size()-1;i++)
{
lists[i+1]=mergeTwoLists(lists[i+1],lists[i]);
}
return lists[i];
}
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if(!l1) return l2;
if(!l2) return l1;
ListNode dummy(-1);
dummy.next=l1;
ListNode *pre=&dummy;
ListNode *p1=l1,*p2=l2,*p2Next=0;
while(p1 && p2)
{
if(p1->val<=p2->val)
{
pre=p1;
p1=p1->next;
}
else
{
p2Next=p2->next;
pre->next=p2;
p2->next=p1;
p2=p2Next;
pre=pre->next;
}
}
if(p2)
{
pre->next=p2;
}
return dummy.next;
}
};
Merge k Sorted Lists
最新推荐文章于 2024-04-03 21:24:25 发布