// 解法一:计算链表长度之差k
// 长的先走k步
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* node=nullptr;
int lenA=getLen(headA);
int lenB=getLen(headB);
if(lenA==0 || lenB==0) return nullptr;
ListNode* preA=headA,*preB=headB;
int flag=lenA-lenB;
if(flag>0){
while(flag-->0)
preA=preA->next;
}
else{
while(flag++<0)
preB=preB->next;
}
while(preA && preB &&preA!=preB){
preA=preA->next;
preB=preB->next;
}
node=preA;
return node;
}
int getLen(ListNode* l){
int len=0;
for(ListNode* start=l;start!=nullptr;start=start->next){
len++;
}
return len;
}
};
// 解法二:交替循环
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* you=headA,*she=headB;
while(you && she){
if(you==she) return you;
you=you->next;
she=she->next;
if(you==nullptr && she==nullptr) break;
if(you==nullptr) you=headB;
if(she==nullptr) she=headA;
}
return nullptr;
}
};