题目:
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
代码:
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if (NULL == pHead1)
{
return pHead2;
}
if(NULL == pHead2)
{
return pHead1;
}
ListNode* Head = new ListNode(-1);
ListNode* Tmp = Head;
ListNode* pHead1_tmp = pHead1;
ListNode* pHead2_tmp = pHead2;
while(NULL != pHead1_tmp && NULL != pHead2_tmp)
{
if(pHead1_tmp->val < pHead2_tmp->val)
{
Tmp->next = pHead1_tmp;
pHead1_tmp = pHead1_tmp->next;
}
else
{
Tmp->next = pHead2_tmp;
pHead2_tmp = pHead2_tmp->next;
}
Tmp = Tmp->next;
}
Tmp->next = NULL != pHead1_tmp ? pHead1_tmp : pHead2_tmp;
return Head->next;
}
};