题解 | #合并两个排序的链表#
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
ji
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
ListNode* p= new ListNode(0);
ListNode* ForReturn=p;
//ListNode* q= new ListNode(0);
//q->next=pHead2;
ListNode* a=pHead1;
//cout<<a->val;
ListNode* b=pHead2;
//cout<<a->val;
while (a!=nullptr&&b!=nullptr)
{
cout<<a->val<<endl;
cout<<b->val<<endl;
if (a->val<=b->val)
{
p->next=a;
//if (a!=nullptr)
a=a->next;
}
else
{
p->next=b;
if (b!=nullptr)
b=b->next;
}
p=p->next;
}
while(a!=nullptr)
{
p->next=a;
a=a->next;
p=p->next;
}
while(b!=nullptr)
{
p->next=b;
b=b->next;
p=p->next;
}
return ForReturn->next;
}
};