题目:
输入两个递增排序的链表,合并这两个链表并使得新链表中的节点仍然是按照递增排序的。
基本思想:
当我们得到两个链表中值较小的头结点并把它连接到已经合并的链表之后,两个链表剩余的节点依然是排序的,因此合并的步骤和之前的而不周是一样的。这就是典型的递归的过程。
#include <iostream>
using namespace std;
typedef int ElemType;//数据类型模板
typedef struct Node//结点
{
ElemType data;
struct Node *next;
}Node;
typedef struct Node * LinkList;
//////////建表
Node* creat_Link(Node *head)
{
int x;
Node *p,*q;
head=(Node *)malloc(sizeof(Node));
head->next=NULL;
q=head;
cin>>x;
while(x!=999)
{
p=(Node *)malloc(sizeof(Node));
p->data=x;
p->next=NULL;
q->next=p;
q=p;
cin>>x;
}
return head;//建完表后返回头结点
}
//////////输出
void output_Link(Node * head)
{
if(head==NULL)
{
cout<<"空链表!"<<endl;
return;
}
Node *q;
q= head->next;
while(q!=NULL)
{
cout<<q->data<<" ";
q=q->next;
}
cout<<endl;
}
Node * foo(Node *head1,Node *head2)
{
if(head1==NULL)
return head2;
else if(head2==NULL)
return head1;
Node * pResult=NULL;
if(head1->data < head2->data)
{
pResult=head1;
pResult->next=foo(head1->next,head2);
}
else
{
pResult=head2;
pResult->next=foo(head1,head2->next);
}
return pResult;
}
void main()
{
Node *head1=NULL;
Node *head2=NULL;
Node * pHead1=creat_Link(head1);//建表
Node * pHead2=creat_Link(head2);
output_Link(pHead1);//输出
output_Link(pHead2);
Node * result = foo(pHead1,pHead2);
output_Link(result->next);
}
原文:http://blog.csdn.net/wtyvhreal/article/details/45624491