// get the len of a linked list
int getLen(ListNode *head) {
int len = 0;
while(head) { len++; head = head>next; }
return len;
}
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (!headA  !headB) return NULL;
ListNode *p1 = headA, *p2 = headB;
int lenA = getLen(headA), lenB = getLen(headB);
if (lenA <= lenB) {
for (int i = 0; i < lenB  lenA; ++i)
p2 = p2>next;
}
else {
for (int i=0; i < lenA  lenB; ++i)
p1 = p1>next;
}
while (p1 && p2 && p1 != p2) p1 = p1>next, p2 = p2>next;
if (!p1  !p2) return NULL;
return p1;
}
O(n) time, O(1) space solution, differ from the official one


I solved it in a similar way:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { int lenA = getLen(headA); int lenB = getLen(headB); int diff = abs(lenA  lenB); ListNode *&longer = lenA > lenB ? headA : headB; for (int i = 0; i < diff; i++) longer = longer>next; while (headA != NULL && headB != NULL && headA != headB) { headA = headA>next; headB = headB>next; } return headA; } static int getLen(ListNode *parent) { int count = 0; while (parent != NULL) { count++; parent = parent>next; } return count; }