/**
* Definition for singlylinked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
struct ListNode *p1,*p2;
p1 = headA;
p2 = headB;
while ((p1 != NULL  p2 != NULL) && p1 != p2)
{
p1 = p1 ? p1>next : headB;
p2 = p2 ? p2>next : headA;
}
return p1;
}
Solution in C


@i4never
for condition check,while ((p1 != NULL  p2 != NULL) && p1 != p2)
is too much.
just usep1 != p2
, because if no intersection exists,p1
andp2
will meet each other when they are bothNULL
.if you consider that maybe
headA
isNULL
andheadB
is a long linked list, then putif (!headA  !headB) return NULL
at the beginning.
