已知两个链表head1 和 head2 都各自升序排序,请合成一个链表并且依然有序。使用递归和非递归方法如下:
用递归方法:
#include<iostream>
using namespace std;
typedef struct node
{
int data;
struct node *next;
}Node;
Node *Merge(Node *head1,Node*head2)
{
Node *head=NULL;
if (head1==NULL)
{
return head2;
}
if (head2==NULL)
{
return head1;
}
if (head1->data<head2->data)
{
head=head1;
head->next=Merge(head1->next,head2);
}
else
{
head=head2;
head->next=Merge(head1,head2->next);
}
return head;//注意这里返回的是第一个节点
}
int main(int argc,char *argv[])
{
Node *head1,*temp1,*p,*q,*temp2,*head2,*temp;
int i;
head1=(Node*)malloc(sizeof(Node));
head2=(Node*)malloc(sizeof(Node));
temp=(Node*)malloc(sizeof(Node));
p=temp1=head1;
q=temp2=head2;
for (i=0;i<5;i++)
{
temp->data=i+1;
head1->next=temp;
head1=temp;
temp=(Node*)malloc(sizeof(Node));
}
head1->next=NULL;
for (i=0;i<7;i++)
{
temp->data=i+2;
head2->next=temp;
head2=temp;
temp=(Node*)malloc(sizeof(Node));
}
head2->next=NULL;
cout<<"合并前:head1"<<endl;
temp1=temp1->next;
while (temp1!=NULL)
{
cout<<temp1->data<<" ";
temp1=temp1->next;
}
cout<<endl<<"合并前:head2"<<endl;
temp2=temp2->next;
while (temp2!=NULL)
{
cout<<temp2->data<<" ";
temp2=temp2->next;
}
cout<<endl;
temp=Merge(p->next,q->next);
cout<<endl<<"合并之后:head"<<endl;
while (temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<endl;
free(temp);
free(head1);
free(head2);
return 0;
}
运行结果:
合并前:head1
1 2 3 4 5
合并前:head2
2 3 4 5 6 7 8
合并之后:head
1 2 2 3 3 4 4 5 5 6 7 8
非递归方法如下:
#include<iostream>
using namespace std;
typedef struct node
{
int data;
struct node *next;
}Node;
Node *Merge(Node *head1,Node*head2)
{
Node *head=(Node*)malloc(sizeof(Node));
Node *temp=head;
if (NULL == head1)
{
return head2;
}
else
{
if (NULL == head2)
{
return head1;
}
}
while (head1!=NULL&&head2!=NULL)
{
if (head1->data<head2->data)
{
temp->next=head1;
temp=temp->next;
head1=head1->next;
}
else
{
temp->next=head2;
temp=temp->next;
head2=head2->next;
}
}
if (NULL==head1)
{
temp->next=head2;
}
else
{
temp->next=head1;
}
return head->next;
}
int main(int argc,char *argv[])
{
Node *head1,*temp1,*p,*q,*temp2,*head2,*temp;
int i;
head1=(Node*)malloc(sizeof(Node));
head2=(Node*)malloc(sizeof(Node));
temp=(Node*)malloc(sizeof(Node));
p=temp1=head1;
q=temp2=head2;
for (i=0;i<5;i++)
{
temp->data=i+1;
head1->next=temp;
head1=temp;
temp=(Node*)malloc(sizeof(Node));
}
head1->next=NULL;
for (i=0;i<7;i++)
{
temp->data=i+2;
head2->next=temp;
head2=temp;
temp=(Node*)malloc(sizeof(Node));
}
head2->next=NULL;
cout<<"合并前:head1"<<endl;
temp1=temp1->next;
while (temp1!=NULL)
{
cout<<temp1->data<<" ";
temp1=temp1->next;
}
cout<<endl<<"合并前:head2"<<endl;
temp2=temp2->next;
while (temp2!=NULL)
{
cout<<temp2->data<<" ";
temp2=temp2->next;
}
cout<<endl;
temp=Merge(p->next,q->next);
cout<<endl<<"合并之后:head"<<endl;
while (temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<endl;
free(temp);
free(head1);
free(head2);
return 0;
}