您的位置:首页 > 职场人生

【剑指offer 面试题17】合并两个排序的链表

2015-06-22 15:20 561 查看
思路:

  比较两个链表端点值的大小,通过递归的方式排列。

#include <iostream>
using namespace std;

struct ListNode
{
int val;
ListNode *next;
ListNode(int v = 0):val(v), next(NULL){}
};

ListNode *SortedListMerge(ListNode *phead1, ListNode *phead2)
{
if(phead1 == NULL)
return phead2;
else if(phead2 == NULL)
return phead1;

ListNode *pMergedHead = NULL;

if(phead1->val < phead2->val)
{
pMergedHead = phead1;
pMergedHead->next = SortedListMerge(phead1->next, phead2);
}
else
{
pMergedHead = phead2;
pMergedHead->next = SortedListMerge(phead1, phead2->next);
}

return pMergedHead;
}

int main()
{

ListNode *l1 = new ListNode(1);
ListNode *h1 = l1;
for(int i = 3; i <= 11; i += 2)
{
ListNode *temp = new ListNode(i);
l1->next = temp;
l1 = l1->next;
}

ListNode *l2 = new ListNode(2);
ListNode *h2 = l2;
for(int i = 4; i <= 12; i += 2)
{
ListNode *temp = new ListNode(i);
l2->next = temp;
l2 = l2->next;
}

cout<<"List1: ";
ListNode *print1 = h1;
while(print1 != NULL)
{
cout<<print1->val<<" ";
print1 = print1->next;
}
cout<<endl;

cout<<"List2: ";
ListNode *print2 = h2;
while(print2 != NULL)
{
cout<<print2->val<<" ";
print2 = print2->next;
}
cout<<endl;

ListNode *mergeList = SortedListMerge(h1, h2);

cout<<"ListMerge: ";
ListNode *printlist = mergeList;
while(printlist != NULL)
{
cout<<printlist->val<<" ";
printlist = printlist->next;
}
cout<<endl;

}


测试结果:

List1: 1 3 5 7 9 11
List2: 2 4 6 8 10 12
ListMerge: 1 2 3 4 5 6 7 8 9 10 11 12
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: