/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <cstdlib>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
ListNode* Merge(ListNode* l1, ListNode* l2) {
// 创建一个虚拟头节点
auto dummy = new ListNode(-1);
ListNode* curr = dummy;
// 遍历两个链表,选择较小的节点添加到结果链表中
while (l1 && l2) {
if (l1->val < l2->val) {
curr->next = l1;
l1 = l1->next;
} else {
curr->next = l2;
l2 = l2->next;
}
curr = curr->next;
}
// 将剩余节点添加到结果链表中
if (l1) {
curr->next = l1;
} else if (l2) {
curr->next = l2;
}
// 返回结果链表的头节点(跳过虚拟头节点)
return dummy->next;
}
};