您的位置:首页 > 其它

合并两个排序的链表

2016-03-29 15:43 323 查看
题目描述:

  输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

算法思想:

  这个题目的思想是通过两个指针分别指向两个链表,递归比较两个链表的值得大小,然后赋值给新建的头结点。直到结束。这里需要注意的就是,我们需要检查两个传进来的链表是否为空;

算法实现:

#include<iostream>
#include<stdlib.h>
using namespace std;

typedef struct ListNode{
int data;
struct ListNode *next;
}ListNode;

ListNode * Merge(ListNode *pHead1, ListNode *pHead2){
11     if(pHead1 == NULL){                     //检查是否为空
12         return pHead2;
13     }
14     if(pHead2 == NULL){
15         return  pHead1;
16     }

ListNode *pHead = NULL;

if(pHead1->data < pHead2->data){           //递归合并两个链表
pHead = pHead1;
pHead->next = Merge(pHead1->next, pHead2);
}
else{
pHead = pHead2;
pHead->next = Merge(pHead1, pHead2->next);
}

return pHead;
}

ListNode *CreateList(int x){                              //创建链表
long num;
ListNode *pHead = NULL;
ListNode *p = NULL;

while(x-- > 0){
cin>>num;
ListNode* pNew = new ListNode();
if(pNew == NULL){
exit(EXIT_FAILURE);
}
pNew->data = num;
pNew->next = NULL;

if(pHead == NULL)
{
pHead = pNew;
p = pHead;
}
else
{
p->next = pNew;
p = p->next;
}
}
return pHead;
}

int main(){
int m, n;

ListNode *p1 = NULL;
ListNode *p2 = NULL;
ListNode *result = NULL;

while(cin>>m>>n){
p1 = CreateList(m);
p2 = CreateList(n);
result = Merge(p1, p2);

if(result == NULL){
cout<<"NULL"<<endl;
}
else{
ListNode *index = result;
while(index != NULL){
cout<<index->data<<' ';
index = index->next;
}
cout<<endl;
}
}
}


参考数据:

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