题目描述:
带头结点的单链表,寻找两个链表的共同后缀的起始位置。
算法思想:
双指针法
核心代码:
//双指针法
int Length(LNode* L)//注意:这里之前写成了int Length(LNode* &L)用的引用。
//这样的话,head1和head2最后都会变成NULL。难怪执行不对。
{
int k=0;
while(L!=NULL)
{
k++;
L=L->next;
}
return k;
}
LNode* Find_Pubilc_Node(LNode* &head1,LNode* &head2)//不带头结点
{
int len1=Length(head1);
int len2=Length(head2);
int longlen,shortlen;
LNode *longlist,*shortlist;
if(len1>len2)
{
longlen=len1;//或者不用记录longlen,shortlen。在这里直接算出差值k。
shortlen=len2;
longlist=head1;
shortlist=head2;
}
else
{
longlen=len2;
shortlen=len1;
longlist=head2;
shortlist=head1;
}
int k=longlen-shortlen;
while((k--)!=0)//这里忘记--了
{
longlist=longlist->next;
}
//while(longlist&&shortlist&&longlist->data!=shortlist->data)这里不是找相同的值
while(longlist!=NULL)
{
if(longlist==shortlist)
return longlist;
else
{
longlist=longlist->next;
shortlist=shortlist->next;
}
}
return NULL;
}
LNode* Find_Pubilc_Node_2(LNode* &head1,LNode* &head2)//不带头结点
{
int len1=Length(head1);
int len2=Length(head2);
LNode *longlist,*shortlist;
int dist=0;