您的位置:首页 > 其它

Microsoft100——005.合并两个已经排序好的链表

2014-09-10 16:30 253 查看
#include<iostream>

using namespace std;

struct ListNode
{
int value;
ListNode *next;
};

ListNode* AddToTail(ListNode *pHead,int value)
{
ListNode *pNew = new ListNode;
pNew->value = value;
pNew->next = NULL;
if (pHead == NULL)
{
pHead = pNew;
}
else
{
ListNode *pNode = pHead;
while(pNode->next != NULL)
{
pNode = pNode->next;
}
pNode->next = pNew;
}
return pHead;
}

void printList(ListNode *pHead)
{
ListNode *temp = pHead;
while(temp!=NULL)
{
cout<<temp->value<<endl;
temp = temp->next;
}
}

ListNode *MergeList(ListNode *pHead1,ListNode *pHead2)
{
if (pHead1 == NULL)
return pHead2;
if (pHead2 == NULL)
return pHead1;
ListNode *pMergeList = NULL;
if (pHead1->value <= pHead2->value)
{
pMergeList = pHead1;
pMergeList->next = MergeList(pHead1->next,pHead2);
}
if (pHead1->value > pHead2->value)
{
pMergeList = pHead2;
pMergeList->next = MergeList(pHead1,pHead2->next);
}
return pMergeList;
}

void main()
{
ListNode *pHead1=NULL,*pHead2=NULL,*pHead=NULL;
for (int i=1 ; i<10 ; i=i+2)
{
pHead1 = AddToTail(pHead1,i);
}
for (i=2 ; i<10 ; i=i+2)
{
pHead2 = AddToTail(pHead2,i);
}
pHead = MergeList(pHead1,pHead2);
printList(pHead);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: