pHead1,pHead2都是单调递增链表,将二者合并成一个单调递增链表
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if (!pHead1 && !pHead2)
return nullptr;
ListNode* merge = nullptr;
while (pHead1 || pHead2)
{
ListNode* t = nullptr;
if (pHead1 && pHead2)
{
if (pHead1->val > pHead2->val)
{
t = pHead2;
pHead2 = pHead2->next;
t->next = nullptr;
}
else
{
t = pHead1;
pHead1 = pHead1->next;
t->next = nullptr;
}
}
else if (pHead1 && !pHead2)
{
t = pHead1;
pHead1 = pHead1->next;
t->next = nullptr;
}
else if (!pHead1 && pHead2)
{
t = pHead2;
pHead2 = pHead2->next;
t->next = nullptr;
}
if (!merge)
merge = t;
else
{
ListNode* tM = merge;
while (tM->next)
tM = tM->next;
tM->next = t;
}
}
return merge;
}