leetcode: 面试题 02.07. Intersection of Two Linked Lists LCCI
原题链接
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int len1 = getLinkedListLen(headA);
int len2 = getLinkedListLen(headB);
ListNode* cur = headA;
ListNode* cur1 = headB;
if (len1 > len2) {
int n = len1 - len2;
while (n--) {
cur = cur->next;
}
} else {
int n = len2 - len1;
while (n--) {
cur1 = cur1->next;
}
}
while (cur != NULL) {
if (cur == cur1) return cur;
cur = cur->next;
cur1 = cur1->next;
}
return NULL;
}
private:
int getLinkedListLen(ListNode* head) {
int len = 0;
ListNode* cur = head;
while (cur != NULL) {
cur = cur->next;
len++;
}
return len;
}
};