leetcode 21 Merge Two Sorted Lists 合并两个有序链表

时间:2023-03-09 08:55:13
leetcode 21 Merge Two Sorted Lists 合并两个有序链表

描述:

合并两个有序链表。

解决:

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (!l1)
return l2;
if (!l2)
return l1;
if (!l1 && !l2)
return NULL; ListNode* ret = new ListNode();
ListNode* now = ret;
while (l1 || l2) {
if (!l1) {
now->next = l2;
break;
}
else if (!l2) {
now->next = l1;
break;
} ListNode** min = l1->val <= l2->val?&l1:&l2;
now->next = *min;
auto save = (*min)->next;
(*min)->next = NULL;
*min = save;
now = now->next;
}
return ret->next;
}