想法:
①遍历a和b求得a和b的长度
②让长的先走abs(lengtha-lengthb)步(长的为cur,短的为pre)
③循环结束条件指向while(cur==NULL||cur==pre)
code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode*cur=headA;
int lengtha=0;
ListNode*pre=headB;
int lengthb=0;
while(cur)
{
cur=cur->next;
lengtha++;
}
while(pre)
{
pre=pre->next;
lengthb++;
}
int subtract=abs(lengtha-lengthb);
if(lengtha<lengthb)
{
cur=headB;
pre=headA;
}
else
{
cur=headA;
pre=headB;
}
while(subtract--)
{
cur=cur->next;
}
while(cur)
{
if(cur==pre)return cur;
else
cur=cur->next;
pre=pre->next;
}
return NULL;
}
};