如题
Snip20181011_2.png如果两个链表存在公共节点,那么从公共节点往后应该都是重合的,因此两条链表呈‘Y’型,
ListNode findFirstCommonNode(LinkList head1, LinkList head2)
{
int len1 = 0, len2=0, diff=0;
LinkNode* p = head1, *q = head2;
while(p){len1++; p=p->next;}
while(q){len2++; q=q->next;}
diff = abs(len1 - len2);
if(len1 > len2)
{
p=head1;
q=head2;
}
else
{
p=head2;
q=head1;
}
while(diff)
{
p=p->next;
diff--;
}
while(p)
{
if(p==q)return p;
p=p->next;
q=q->next;
}
return NULL;
}
网友评论