A concise code using C++


  • -1
    F
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if(!headA || !headB) return nullptr;
        
        ListNode* pNode[2] = {headA, headB};
        
        while(pNode[0] && pNode[1]){
            pNode[0] = pNode[0]->next;
            pNode[1] = pNode[1]->next;
        }
        
        if(!pNode[0]) pNode[0] = headB;
        if(!pNode[1]) pNode[1] = headA;
        
        while(pNode[0] && pNode[1]){
            pNode[0] = pNode[0]->next;
            pNode[1] = pNode[1]->next;
        } 
        
        if(!pNode[0]) pNode[0] = headB;
        if(!pNode[1]) pNode[1] = headA;
        
        while(pNode[0] && pNode[1] && pNode[0]->val != pNode[1]->val){
            pNode[0] = pNode[0]->next;
            pNode[1] = pNode[1]->next;
        }         
        
        return pNode[0];
    }

Log in to reply
 

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