My easy understanding C++ code.


  • 1
    R
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) 
    {
        if (!headA || !headB)
            return NULL;
            
        ListNode *ph = headA;
        int len1 = 0, len2 = 0;
        while (ph)
        {
            ++len1;
            ph = ph->next;
        }
        
        ph = headB;
        while (ph)
        {
            ++len2;
            ph=ph->next;
        }
        
        ListNode *ph2;
        int gap = -1;
        if (len1 >= len2)
        {
            gap = len1 - len2;
            ph = headA;
            ph2 = headB;
        }
        else
        {
            gap = len2 - len1;
            ph = headB;
            ph2 = headA;
        }
        
        
        while(gap > 0)
        {
            ph = ph->next;
            --gap;
        }
        
        while (ph && ph2)
        {
            if (ph == ph2)
                return ph;
            else
            {
                ph = ph->next;
                ph2 = ph2->next;
            }
        }
        
        return NULL;
    }

Log in to reply
 

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