c
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode *tailA=headA;
struct ListNode *tailB=headB;
int count1=0;
int count2=0;
//分别找尾节点,并顺便统计节点数量:
while(tailA)
{
tailA=tailA->next;
count1++;
}
while(tailB)
{
tailB=tailB->next;
count2++;
}
if(tailA!=tailB)//如果尾节点不相同,则一定不相交
return NULL;
int tmp=abs(count1-count2);//得到两个数量差值的绝对值
struct ListNode*longList=headA;
struct ListNode*shortList=headB;
//找出长的链表:
if(count2>count1)
{
longList=headB;
shortList=headA;
}
//先让长的链表走差值步,再和短链表齐头并进
while(tmp)
{
longList=longList->next;
tmp--;
}
//两个链表齐头并进:
while(longList!=shortList)
{
shortList=shortList->next;
longList=longList->next;
}
//两个链表相遇的地方就是节点
return longList;
}