题目:
输入两个递增排序的链表,合并这两个链表并使新链表中的结点仍然是按照递增排序的。例如输入下图中的链表1和链表2,则合并之后的升序链表如链表3所示。
递归:
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if (pHead1 == NULL)
return pHead2;
if (pHead2 == NULL)
return pHead1;
ListNode* pMerageHead = NULL;
if (pHead1->val <= pHead2->val)
{
pMerageHead = pHead1;
pMerageHead->next = Merge(pHead1->next, pHead2);
}
else
{
pMerageHead = pHead2;
pMerageHead->next = Merge(pHead1, pHead2->next);
}
return pMerageHead;
}
};
非递归:
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if (pHead1 == NULL)
return pHead2;
if (pHead2 == NULL)
return pHead1;
ListNode* pTail = NULL;
ListNode* pNewNode = NULL;
//确定头结点的位置
if (pHead1->val <= pHead2->val)
{
pNewNode = pHead1;
pTail = pNewNode;
pHead1 = pHead1->next;
}
else
{
pNewNode = pHead2;
pTail = pNewNode;
pHead2 = pHead2->next;
}
while (pHead1&&pHead2)
{
if (pHead1->val <= pHead2->val)
{
pTail->next = pHead1;
pHead1 = pHead1->next;
}
else
{
pTail->next = pHead2;
pHead2 = pHead2->next;
}
pTail = pTail->next;//尾部向后走一个
}
//一个链表走到末尾,把另一个剩下的连接上去
if (pHead1)
pTail->next = pHead1;
if (pHead2)
pTail->next = pHead2;
return pNewNode;
}
};