链接: https://leetcode-cn.com/problems/intersection-of-two-linked-lists/description/
//1.暴力遍历对比法
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode* tailA=headA;
struct ListNode* tailB=headB;
while(tailA)
{
tailB=headB;
while(tailB)
{
if(tailB==tailA)
{
return tailB;
}
tailB=tailB->next;
}
tailA=tailA->next;
}
return NULL;
}
//2.快慢(先后)指针法 (长链的指针先走长链与短链的差距步)
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
if(headA==NULL&&headB==NULL)
return NULL;
struct ListNode* tailA=headA;
struct ListNode* tailB=headB;
int lenA=1;
int lenB=1;
while(tailA->next!=NULL)
{
lenA++;
tailA=tailA->next;
}
while(tailB->next!=NULL)
{
lenB++;
tailB=tailB->next;
}
//根据最后一个的节点的地址来判断两链是否有相交
int k=abs(lenA-lenB);
if(tailA==tailB)//有交点,相交
{
struct ListNode* shortlist=headA;
struct ListNode* longlist=headB;
if(lenA>lenB)
{
shortlist=headB;
longlist=headA;
}
while(k--)//长链的指针先走长短差距步
{
longlist=longlist->next;
}
while(longlist!=shortlist)//然后再一起走
{
longlist=longlist->next;
shortlist=shortlist->next;
}
return shortlist;
}
return NULL;
}