您的位置:首页 > 编程语言 > C语言/C++

剑指offer面试题25:合并两个排序的链表(c++ 递归+非递归)

2018-03-04 19:39 549 查看
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则
递归AC如下:#include<iostream>
#include<vector>
using namespace std;
struct ListNode
{
int val;
struct ListNode *next;
ListNode(int x):
val(x),next(NULL){}

};
class Solution
{
public:
ListNode *Merge(ListNode *phead1,ListNode *phead2)
{
if(phead1==nullptr)
return phead2;
else if(phead2==nullptr)
return phead1;
ListNode *pMergeHead=nullptr;
if(phead1->val<phead2->val)
{
pMergeHead=phead1;
pMergeHead->next=Merge(phead1->next,phead2);
}
else
{
pMergeHead=phead2;
pMergeHead->next=Merge(phead1,phead2->next);
}
return pMergeHead;
}
};
int main()
{
Solution sol;
ListNode *phead1=new ListNode(1);//链表 1 3 5 7
phead1->next=new ListNode(3);
phead1->next->next=new ListNode(5);
phead1->next->next->next=new ListNode(7);
ListNode *phead2=new ListNode(2);//链表 2 4 6 8
phead2->next=new ListNode(4);
phead2->next->next=new ListNode(6);
phead2->next->next->next=new ListNode(8);
ListNode *phead3;
phead3=sol.Merge(phead1,phead2);

while(phead3!=nullptr)
{
cout<<phead3->val<<" ";
phead3=phead3->next;
}
/*
测试结果 1 2 3 4 5 6 7 8 功能测试成功
*/
}
非递归AC代码如下://合并两个递增增长的链表
//非递归做法

#include<iostream>
#include<vector>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x):
val(x),next(NULL){
}
};
class Solution
{
public:
ListNode *Merge(ListNode *phead1,ListNode *phead2)
{
if(phead1==nullptr)
return phead2;
else if(phead2==nullptr)
return phead1;
ListNode *phead;
ListNode *p;//p为合并的链表的工作指针
//取较小的值作为头节点
if(phead1->val<=phead2->val)
{
phead=phead1;
phead1=phead1->next;
}
else
{
phead=phead2;
phead2=phead2->next;
}
//开始遍历合并
p=ph
4000
ead; //p为合并后的链表的工作指针
while(phead1&&phead2) //当有一个链表到结尾时,循环结束
{
if(phead1->val<=phead2->val) //如果链表1的结点小于链表2的结点
{
p->next=phead1; //取这个结点加入合并链表
phead1=phead1->next; //链表1后移一位
p=p->next; //工作指针后移一位
}
else //否则取链表2的结点
{
p->next=phead2;
phead2=phead2->next;
p=p->next;
}
}
if(phead1==nullptr) //链表1遍历完了
{
p->next=phead2;//如果链表2也遍历完了,则pHead2=NULL
}
if(phead2==nullptr) //链表2遍历完了
{
p->next=phead1;///如果链表1也遍历完了,则pHead1=NULL
}
return phead;
}

};
int main()
{
Solution sol;
ListNode *phead1=new ListNode(1);//链表 1 3 5 7
phead1->next=new ListNode(3);
phead1->next->next=new ListNode(5);
phead1->next->next->next=new ListNode(7);
ListNode *phead2=new ListNode(2);//链表 2 4 6 8
phead2->next=new ListNode(4);
phead2->next->next=new ListNode(6);
phead2->next->next->next=new ListNode(8);
ListNode *phead3;
phead3=sol.Merge(phead1,phead2);

while(phead3!=nullptr)
{
cout<<phead3->val<<" ";
phead3=phead3->next;
}
/*
测试结果 1 2 3 4 5 6 7 8 功能测试成功
*/
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: