今天去面试的一道题,贴出来,慢慢改善。
Node *Merge(Node *head1, Node *head2)
{
Node *p1=head1->next;
Node *p2=head2->next;
Node *head,*tail=null;
While(p1!=null && p2!=null)//当链表不为空,逐个比较建立新的链表;
{
if(p1->data < p2->data)
{
if(tail==null)
{
head->next=p1;
tail=p1;
}
else
{
tail->next=p1;
tail=p1;
}
p1=p1->next;
}
else
{
if(tail==null)
{
head->next=p2;
tail=p2;
}
else
{
tail->next=p2;
tail=p2;
}
p2=p2->next;
}
}
If(p1!=null)//将剩余节点连接起来;
{
Tail->next=p1;
}
Else
{
Tail->next=p2;
}
if(tail==null) //两个链表其中有空的情况;
{
if(p1!=null)
{
head=head1;
}
else if(p2!=null)
{
head=head2;
}
else
{
head=tail;
}
}
return head;
}