兩個指針分別單步遍歷鏈表,當(dāng)訪問到尾部額時候,指向另外一個鏈表的頭繼續(xù)遍歷秦爆,直到兩個指針相遇就返回
對于[1] 兩個都指向[1] 寄症,一開始就出現(xiàn)p1 == p2情況宙彪,需要直接返回p1或者p2
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode *p1 = headA;
struct ListNode *p2 = headB;
if (p1 == NULL || p2 == NULL) return NULL;
while (p1 != NULL && p2 != NULL && p1 != p2) {
p1 = p1->next;
p2 = p2->next;
//
// Any time they collide or reach end together without colliding
// then return any one of the pointers.
//
if (p1 == p2) return p1;
//
// If one of them reaches the end earlier then reuse it
// by moving it to the beginning of other list.
// Once both of them go through reassigning,
// they will be equidistant from the collision point.
//
if (p1 == NULL) p1 = headB;
if (p2 == NULL) p2 = headA;
}
return p1;
}