链表定义
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
合并两个链表
ListNode* mergeTwoLists(ListNode *list1, ListNode *list2) {
if ((!list1) || (!list2))
return list1 ? list1 : list2;
ListNode *head = new ListNode;
ListNode *temp = head, *l1 = list1, *l2= list2;
while (l1 && l2) {
if (l1->val < l2->val) {
temp->next = l1;
l1= l1->next;
}
else {
temp->next = l2;
l2= l2->next;
}
temp = temp->next;
}
temp->next = (l1? l1: l2);
return head->next;
}
合并n个链表
ListNode* mergeTwoLists(ListNode *list1, ListNode *list2) {
if ((!list1) || (!list2))
return list1 ? list1 : list2;
ListNode *head = new ListNode;
ListNode *temp = head, *l1 = list1, *l2= list2;
while (l1 && l2) {
if (l1->val < l2->val) {
temp->next = l1;
l1= l1->next;
}
else {
temp->next = l2;
l2= l2->next;
}
temp = temp->next;
}
temp->next = (l1? l1: l2);
return head->next;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode *res = nullptr;
for (int i = 0; i < lists.size(); ++i) {
res = mergeTwoLists(res, lists[i]);
}
return res;
}