递归:
每一次让下一个节点递归式的链接到新链表之后。
//递归
ListNode* MergeList(ListNode* pHead1,ListNode* pHead2)
{
if(pHead1 == NULL)
return pHead2;
else if(pHead2 == NULL)
return pHead1;
//新链表的头
ListNode* pNewHead = NULL;
if(pHead1->value < pHead2->value)
{
pNewHead = pHead1;
pNewHead->Next = MergeList(pHead1->Next,pHead2);
}
if(pHead1->value > pHead2->value)
{
pNewHead = pHead2;
pNewHead->Next = MergeList(pHead1,pHead2 ->Next);
}
return pNewHead;
}
非递归:
比较大小,链接后此指针在此链表向后走一步,知道某一指针为空时,将另外一链表后续元素全部链接到此链表上。
//非递归
ListNode* MergeList_Nor(ListNode* pHead1,ListNode* pHead2)
{
if(pHead1 == NULL)
return pHead2;
else if(pHead2 == NULL)
return pHead1;
//先给新链表的头
ListNode* pNewHead = NULL;
if(pHead1->value < pHead2 -> value)
{
pNewHead = pHead1;
pHead1=pHead1->Next;
}
else
{
pNewHead = pHead2;
pHead2=pHead2->Next;
}
ListNode* pCurNode = pNewHead->Next;
//链接链表 如果有一个为空的时则停止循环
while(pHead1 != NULL || pHead2 != NULL)
{
if(pHead1->value < pHead2->value)
{
pCurNode= pHead1;
pHead1 = pHead1->Next;
}
else if(pHead1->value > pHead2 -> value)
{
pCurNode = pHead2;
pHead2 = pHead2->Next;
}
//这里pCur都要向后移动
pCurNode = pCurNode->Next;
}
//除了循环要判断是谁先为空
if(pHead1 == NULL)
pCurNode = pHead2;
else if(pHead2 == NULL)
pCurNode = pHead1;
return pNewHead;
}