21. 合并两个有序链表
来自 <https://leetcode.cn/problems/merge-two-sorted-lists/>
/**
* Definition for singly-linked list.
* 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) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode * dummy=new ListNode(-1);
ListNode* ptr=dummy;
if(list1==nullptr){
return list2;
}
if(list2==nullptr){
return list1;
}
while(list1!=nullptr && list2!=nullptr){
if(list1->val<list2->val){
ptr->next=list1;
// ptr=ptr->next;
list1=list1->next;
}else{
ptr->next=list2;
// ptr=ptr->next;
list2=list2->next;
}
ptr=ptr->next;
}
// 扫尾
if(list1!=nullptr){
ptr->next=list1;
}
if(list2!=nullptr){
ptr->next=list2;
}
return dummy->next;
}
};
![image](https://img2022.cnblogs.com/blog/2269816/202210/2269816-20221016183636982-918698286.png)