完全同 AC36. 合并两个排序的序列
讨论中有不同的解法(递归和迭代的简易版)
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
auto dummy = new ListNode(-1), tail = dummy;
while (l1 && l2) {
if (l1->val > l2->val) {
tail = tail->next = l2;
l2 = l2->next;
}
else {
tail = tail->next = l1;
l1 = l1->next;
}
}
// if (l1) tail = tail->next = l1;
// if (l2) tail = tail->next = l2;
// 上面两行代码可以写成如下一行
tail = tail->next = (l1 != NULL ? l1 : l2);
return dummy->next;
}
};