Simple C++ solution (5 lines)

• Move cur1 (cur2) forward from headA (headB) and loop back to headB (headA), eventually cur1 and cur2 will meet at the intersection point or nullptr.

``````ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
while(cur1 != cur2){
}
return cur1;
}``````

• smart!thanks for sharing.

• very impressive

• The time depend on luck?

• This post is deleted!

• of crouse not;

it 's O(m+n);

m,n is length of each list

• Why are u so talent?

• If there is no interaction, it will loop forever.

• Of course not.
Once both cur1 and cur2 have traversed listA and listB, cur1 == cur2 == NULL.
Then loop exits.
Brilliant solution!

• This post is deleted!

• It's basically "m + n == n + m".
How did m * n come about?

• very brilliant solution!

• very smart, thanks for sharing

• can you give and prove the run time complexity about the algorithm?

• @Zhen_Li If length M and length N have overlapping length of K, then both pointers will be moved (M-K) steps if M == N, and moved (M+N-K) steps if M !=N.

• said in Simple C++ solution (5 lines):

while(cur1 != cur2){
}
return cur1;
}

I think u don't need to change the head, why u change the head when reach the NULL? what's the benefit of it?

• @andrewpiggy Agree with you,there's a bug here......

• This post is deleted!

• This post is deleted!

• @Neal_Yang The change to another list head is to make sure each pointer will move exactly the same number of steps before meeting at the common node. In general, the length of the two lists is different, and then the number of steps to move each pointer will be m+n-k, where m and n are the length of two lists and k is the length of overlapping part.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.