LC Hot 100 链表专题 - 21 合并两个有序列表
// 归并排序
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
if (list1 == nullptr)
return list2;
if (list2 == nullptr)
return list1;
auto dummy = new ListNode(-1);
auto cur = dummy;
while(list1 && list2) {
if (list1->val < list2->val) {
cur->next = list1;
list1 = list1->next;
cur = cur->next;
} else {
cur->next = list2;
list2 = list2->next;
cur = cur->next;
}
}
if (list1) {
cur->next = list1;
}
if (list2) {
cur->next = list2;
}
return dummy->next;
}
};