/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
// write code here
if(pHead1==nullptr)//若链表1为空,则返回链表2
{
return pHead2;
}
else if(pHead2==nullptr)//若链表2为空,则返回链表1
{
return pHead1;
}
ListNode *p1,*p2;//指针用于遍历链表
ListNode *head=new ListNode(0);//新建一个带头结点的链表
ListNode *r=head;//尾插法
p1=pHead1;
p2=pHead2;
while(p1!=nullptr&&p2!=nullptr)//当两个链表都非空时才可循环
{
if(p1->val<p2->val)
{
r->next=p1;
r=r->next;
p1=p1->next;
}
else
{
r->next=p2;
r=r->next;
p2=p2->next;
}
}
if(p1!=nullptr)//若链表1还有未合并的元素
{
r->next=p1;
}
else if(p2!=nullptr)//若链表2还有未合并的元素
{
r->next=p2;
}
return head->next;//返回除头节点外剩余部分
}
};