如下图所示



注意:暴力解法效率较低,不建议采用
struct ListNode
{
int val;
struct ListNode *next;
};
typedef struct ListNode ListNode;
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB)
{
ListNode*pcurA=headA;
ListNode*pcurB=headB;
while(pcurA)
{
pcurB=headB;
while(pcurB)
{
if(pcurA==pcurB)
return pcurA;
pcurB=pcurB->next;
}
pcurA=pcurA->next;
}
return NULL;
} struct ListNode
{
int val;
struct ListNode *next;
};
typedef struct ListNode ListNode;
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB)
{
ListNode*pcurA=headA;
ListNode*pcurB=headB;
int countA=0;
int countB=0;
while(pcurA)//求出链表长度
{
pcurA=pcurA->next;
countA++;
}
while(pcurB)
{
pcurB=pcurB->next;
countB++;
}
int tmp=abs(countA-countB);//长度差值
ListNode*slow,*fast;
if(countA<countB)
{
slow=headA;
fast=headB;
}
else
{
slow=headB;
fast=headA;
}
while(tmp--)//长链表先走差值的步数
{
fast=fast->next;
}
while(fast&&slow)//同步比较
{
if(fast==slow)
return fast;
fast=fast->next;
slow=slow->next;
}
return NULL;
}