思路:写出mergetwo,不断合并(比较好想好写) mergetwo 当 p q都不为空的时候,根据两者大小选择连哪一个,被选择的移到下一个,直到p q其中有一个为空,最后连上不为空的那一条
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode* head = NULL;
for(auto&node:lists){
head = mergetwo(head,node);
}
return head;
}
ListNode* mergetwo(ListNode*p,ListNode*q){
if(!p)return q;
if(!q)return p;
ListNode* dummy = new ListNode(-1);
ListNode* head = dummy;
while(p&&q){
if(p->val<=q->val){
head->next = p;
p = p->next;
}else{
head->next = q;
q = q->next;
}
head =head->next;
}
head->next = q?q:p;
ListNode*res = dummy->next;
return res;
}
};
|