思路:
先求出两个链表的长度差
长链表先走差距步
同时走,第一个地址相同的是交点
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode* tailA = headA,* tailB = headB;
int lenA = 1, lenB = 1;
while(tailA->next)
{
tailA = tailA->next;
++lenA;
}
while(tailB->next)
{
tailB = tailB->next;
++lenB;
}
if(tailA != tailB)
{
return NULL;
}
int gap = abs(lenA - lenB);
struct ListNode* longList = headA,* shortList = headB;
if(lenA<lenB)
{
longList = headB;
shortList = headA;
}
while(gap--)
{
longList= longList->next;
}
while(longList !=shortList)//比较的是地址
{
longList = longList->next;
shortList = shortList->next;
}
return longList;
}
标签:结点,ListNode,struct,tailA,next,链表,longList,Leetcode,tailB
From: https://blog.51cto.com/u_15992140/6218844