1.题目描述:
输入两个递增排序的链表,合并这两个链表并使新链表中的结点仍然是按照递增排序的。链表结点定义如下:
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
2.分析:
1)考虑代码鲁棒性的问题。a.第一个链表为空链表;b.第二个链表为空链表;c.两个链表都为空链表.
3.源代码:
// Copyright (c) 2015年 skewrain. All rights reserved.
#include <iostream>
#include <stdio.h>
#include <stack>
using namespace std;
struct ListNode
{
int m_nValue;
ListNode *m_pNext;
};
ListNode* CreateLink(int a[],int k)
{
ListNode *Head = NULL,*q = NULL;
for (int i=0; i<k; i++)
{
ListNode *pNew = new ListNode();
pNew->m_nValue = a[i];
pNew->m_pNext = NULL;
if(Head==NULL)
{
Head = pNew;
q = pNew;
}
else
{
q->m_pNext = pNew;
q = pNew;
}
}
return Head;
}
//从头到尾打印列表
void printLink(ListNode *pHead)
{
cout<<"链表内容为:";
ListNode *p = pHead;
while (p) {
cout<<p->m_nValue<<" ";
p=p->m_pNext;
}
cout<<endl;
}
ListNode* Merge(ListNode* pHead1,ListNode* pHead2)
{
if(pHead1 == NULL)
return pHead2;
if(pHead2 == NULL)
return pHead1;
ListNode* pMergeHead = NULL;
if(pHead1->m_nValue < pHead2->m_nValue)
{
pMergeHead = pHead1;
pMergeHead->m_pNext = Merge(pHead1->m_pNext,pHead2);
}
else
{
pMergeHead = pHead2;
pMergeHead->m_pNext = Merge(pHead1, pHead2->m_pNext);
}
return pMergeHead;
}
int main(int argc,char *argv[]){
int a[]={1,3,5,7};
ListNode *ptr1 = CreateLink(a,4);
cout<<"合并之前的a";
printLink(ptr1);
int b[]={2,4,6,8};
ListNode *ptr2 = CreateLink(b,4);
cout<<"合并之前的b";
printLink(ptr2);
ListNode *c = Merge(ptr1,ptr2);
cout<<"合并之后的c";
printLink(c);
return 0;
}