Q160. Intersection of Two Linked Lists
Last updated
Last updated
/**
* 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 || headB==NULL) return NULL;
int lenA = 0, lenB = 0;
ListNode* lA = headA;
ListNode* lB = headB;
while(lA){
lA = lA->next;
lenA++;
}
while(lB){
lB = lB->next;
lenB++;
}
lA = headA; lB = headB;
if(lenA > lenB){
for(int i = 0; i<lenA-lenB; i++) lA = lA->next;
}else{
for(int i = 0; i<lenB-lenA; i++) lB = lB->next;
}
while(lA != lB){
lA = lA->next;
lB = lB->next;
}
return lA;
}
};