/**
* 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) {
if(headA == NULL or headB == NULL){
return NULL;
}
int lenA = 1, lenB = 1;
ListNode* pA = headA;
ListNode* pB = headB;
int dis = 0;
while(pA->next != NULL){
pA = pA->next;
lenA++;
}
while(pB->next != NULL){
pB = pB->next;
lenB++;
}
pA = headA;
pB = headB;
if(lenB > lenA){
dis = lenB -lenA;
while(dis != 0){
pB = pB->next;
dis--;
}
}
else{
dis = lenA - lenB;
while(dis != 0){
pA = pA->next;
dis--;
}
}
if(pA->val == pB->val){
return pA;
}
while(pA->next != NULL && pB->next != NULL){
pA = pA->next;
pB = pB->next;
if(pA->val == pB->val){
return pA;
}
}
return NULL;
}
};
计算两个链表的长度差,要是有重合的话,一定是从长的那个链表减去长度差的节点开始重合的。