题目


知识点
三目运算符的不等利用
cur->next = list1 != nullptr ? list1 : list2;

思路
链接K神有ppt
错误
题解
cpp
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode* dum = new ListNode(0);//伪头节点
ListNode* cur = dum;//cur是最终链表的移动指针
while (list1 != nullptr && list2 != nullptr) {
if (list1->val < list2->val) {
cur->next = list1;
list1 = list1->next;
}
else {
cur->next = list2;
list2 = list2->next;
}
cur = cur->next;//一定要有的一步,拿到外面写
}
cur->next = list1 != nullptr ? list1 : list2;
//等价的if-else写法
//if (list1 != nullptr)
// cur->next = list1;
//else
// cur->next = list2;
return dum->next;
}
};