题目描述
法一 顺序合并
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2){
ListNode* dummy = new ListNode(-1); //创建一个新的头节点
ListNode *cur=dummy, *aPtr = l1, *bPtr = l2;
while(aPtr && bPtr){
if(aPtr->val < bPtr->val){
dummy->next = aPtr;
aPtr = aPtr->next;
} else {
dummy->next = bPtr;
bPtr = bPtr->next;
}
dummy = dummy->next;
}
dummy->next = aPtr ? aPtr : bPtr;
return cur->next;
}
ListNode* mergeKLists(vector<ListNode*>& lists){
ListNode* ans = nullptr;
for(int i=0;i<lists.size();i++) {
ans = mergeTwoLists(ans, lists[i]);
}
return ans;
}
};