My C++ Solution


  • 1
    X
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
            int lenA=0,lenB=0;
            ListNode *p=headA,*q=headB;
            while (p) {
                p=p->next;
                lenA ++;
            }
            while (q) {
                q=q->next;
                lenB ++;
            }
            int gap = abs(lenA-lenB);
            p=headA,q=headB;
            while (gap -- ) {
                if (lenA > lenB) {
                    p=p->next;
                }
                if (lenA <lenB) {
                    q=q->next;
                }
            }
            while (p && q) {
                if (p == q) {
                    return p;
                }
                p=p->next;
                q=q->next;
            }
            return NULL;
        }

Log in to reply
 

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