主要思路:寻找两个链表之间长度的差值。让长的链表移动一定的差值距离,使得此时两个指针遍历的长度一致,如果在遍历的过程中出现两个指针相等,说明存在相同节点。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
int len1 = 0, len2 = 0, sub = 0;
ListNode* cur1 = pHead1, *cur2 = pHead2;
while (cur1 != NULL) {
len1++;
cur1 = cur1->next;
}
while (cur2 != NULL) {
len2++;
cur2 = cur2->next;
}
cur1 = pHead1;
cur2 = pHead2;
sub = abs(len1 - len2);
if (len1 > len2) {
while (sub--) {
cur1 = cur1->next;
}
} else {
while (sub--) {
cur2 = cur2->next;
}
}
while (cur1 != NULL && cur2 != NULL) {
if (cur1 == cur2) {
return cur1;
}
cur1 = cur1->next;
cur2 = cur2->next;
}
return NULL;
}
};