解法一:
Node *ListMerge1(Node *head1,Node *head2)//采用递归的方法实现
{
if(head1==NULL)
return head2;
if(head2==NULL)
return head1;
Node *head=NULL;
if(head1->value < head2->value)
{
head=head1;
head->next=ListMerge1(head1->next,head2);
}
else
{
head=head2;
head->next=ListMerge1(head1,head2->next);
}
return head;
}
解法二:
Node *ListMerge(Node *head1,Node *head2)
{
if(!head1) return head2;
if(!head2) return head1;
Node *head=NULL;//合并后的头指针
Node *p1=head1;//p1用于扫描链表1
Node *p2=head2;//p2用于扫描链表2
if(head1->value<head2->value)
{
head=head1;
p1=head1->next;
}
else
{
head=head2;
p2=head2->next;
}
Node *p=head;//p永远指向最新合并的结点
while(p1 && p2)//如果循环停止,则p1或p2至少有一个为NULL
{
if(p1->value<p2->value)
{
p->next=p1;
p1=p1->next;
}
else
{
p->next=p2;
p2=p2->next;
}
p=p->next;
}
if(p1)//如果链1还没走完
{
p->next=p1;
}
else if(p2)//如果链2还没走完
{
p->next=p2;
}
return head;
}