思路:计算出两个单链表的长度,再使用较长的减去较短的,让较长的先走两个链表长度的差值的步数,然后俩个链表同时走,每走一步判断地址是否相等,若相等,则为交点,不相等则没有交点。
void crossList(List* phead_1, List* phead_2)
{assert(phead_1);
assert(phead_2);
List* phead_1_1 = phead_1;
List* phead_2_2 = phead_2;
int count_1 = 0;
int count_2 = 0;
int dif = 0;
while (phead_1_1)
{
phead_1_1 = phead_1_1->next;
count_1++;
}
while (phead_2_2)
{
phead_2_2 = phead_2_2->next;
count_2++;
}
phead_1_1 = phead_1;
phead_2_2 = phead_2;
if (count_1 < count_2)
{
dif = count_2 - count_1;
while (dif>0)
{
phead_2_2 = phead_2_2->next;
dif--;
}
}
if (count_1 > count_2)
{
dif = count_1 - count_2;
while (dif > 0)
{
phead_1_1 = phead_1_1->next;
dif--;
}
}
while (phead_1_1 != NULL&&phead_2_2 != NULL)
{
if (phead_1_1 == phead_2_2)
{
printf("有交点,交点处的数据为:%d \n", phead_1_1->arrary);
break;
}
phead_1_1 = phead_1_1->next;
phead_2_2 = phead_2_2->next;
}
}