题目:输入两个递增的链表,合并这两个链表并使新链表的节点仍然是递增排序的。
c++实现:
ListNode* merge(ListNode* pHead1, ListNode* pHead2)
{
if(pHead1==NULL)
return pHead2;
else if(pHead2==NULL)
{
return pHead1;
}
ListNode* root = NULL;
ListNode* current = NULL;
while(pHead1!=NULL && pHead2!=NULL)
{
if(pHead1->m_nkey<=pHead2->m_nkey)
{
if(root==NULL)
{
current = pHead1;
root = current;
}
else{
current->m_pNext = pHead1;
current = current->m_pNext;
}
pHead1 = pHead1->m_pNext;
}
else
{
if(root==NULL)
{
current = pHead2;
root = current;
}
else{
current->m_pNext = pHead2;
current = current->m_pNext;
}
pHead2 = pHead2->m_pNext;
}
}
if(pHead1!=NULL)
current->m_pNext = pHead1;
if(pHead2!=NULL)
{
current->m_pNext = pHead2;
}
return root;
}
JAVA实现: