class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(0 == headA || headB == 0)
return NULL;
int len1 = 0, len2 = 0;
ListNode *p;
for(p = headA; p != NULL; p = p->next, ++len1);
for(p = headB; p != NULL; p = p->next, ++len2);
ListNode *p1 = headA, *p2 = headB;
if(len1 > len2){
int gap = len1 - len2;
while(gap--){
p1 = p1->next;
}
}else if(len2 > len1){
int gap = len2 - len1;
while(gap--){
p2 = p2->next;
}
}
while(p1 && p2){
if(p1 == p2)
return p1;
p1 = p1->next; p2 = p2->next;
}
return NULL;
}
};
160. Intersection of Two Linked Lists
最新推荐文章于 2021-06-04 08:35:26 发布