https://leetcode.cn/problems/merge-two-sorted-lists/description/
/**
* 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* newHead = new ListNode(0); // 初始化一个新的头节点
ListNode* cur = newHead;
while (list1 != nullptr && list2 != nullptr) {
if (list1->val < list2->val) {
cur->next = list1;
cur = list1;
list1 = list1->next;
} else {
cur->next = list2;
cur = list2;
list2 = list2->next;
}
}
if (list1 != nullptr) {
cur->next = list1;
} else if (list2 != nullptr) {
cur->next = list2;
}
return newHead->next; //返回新链表的头节点
}
};