1、题目描述
输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是按照递增排序的。
例如输入如图所示的链表1和链表2,则合并之后的升序链表如链表3所示。链表节点定义如下:
struct ListNode{
int m_nValue;
ListNode* m_pNext;
};
2、方法一:循环合成链表
循环合成链表,在原来链表的基础上修改节点的next域指向,合成新的链表。
首先设置两个指针,一个pNewHead指向新链表的头结点,一个指针pTailNode指向新链表的最后一个节点。
最后将剩下的某个链表直接连接到新链表上。
3、源码
ListNode* Merge(ListNode* pHead1,ListNode* pHead2){
if(NULL == pHead1)
return pHead2;
if(NULL == pHead2)
return pHead2;
ListNode* pNewHead=NULL;
ListNode* pTailNode=NULL;
ListNode* pCur1=pHead1;
ListNode* pCur2=pHead2;
if(pCur1->m_nValue<pCur2->m_nValue){
pNewHead=pCur1;
pTailNode=pCur1;
pCur1=pCur1->m_pNext;
}
else{
pNewHead=pCur2;
pTailNode=pCur2;
pCur2=pCur2->m_pNext;
}
while(pCur1&&pCur2){
if(pCur1->m_nValue<pCur2->m_nValue){
pTailNode=pCur1;
pCur1=pCur1->m_pNext;
}
else{
pTailNode=pCur2;
pCur2=pCur2->m_pNext;
}
pTailNode=pTailNode->m_pNext;
}
if(pCur1)
pTailNode->m_pNext=pCur1;
if(pCur2)
pTailNode->m_pNext=pCur2;
return pNewHead;
}
方法二:递归合成新链表
#include<iostream>
#include<stdio.h>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
ListNode* Merge1(ListNode* pHead1, ListNode* pHead2)
{
if (NULL == pHead1 && NULL == pHead2)
return NULL;
if (NULL == pHead1)
return pHead2;
if (NULL == pHead2)
return pHead1;
ListNode* pNewHead = NULL;
if (pHead1->m_nValue < pHead2->m_nValue){
pNewHead = pHead1;
pNewHead->m_pNext = Merge1(pHead1->m_pNext, pHead2);
}
else{
pNewHead = pHead2;
pNewHead->m_pNext = Merge1(pHead1, pHead2->m_pNext);
}
return pNewHead;
}