Share a straightforward solution in clean C codes


  • 0
    T
    struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
     
        int len1 = 0;
        int len2 = 0;
     
        if(!headA || !headB) return NULL;
        
        struct ListNode *p1 = headA;
        struct ListNode *p2 = headB;
        
        for(; headA; len1++, headA = headA->next);
        for(; headB; len2++, headB = headB->next);
        
        if(len1 > len2)
            for(int i=0; i<len1-len2; i++, p1 = p1->next);
        else
            for(int j=0; j<len2-len1; j++, p2 = p2->next);
    
        for(; p1&&p2; p1=p1->next, p2=p2->next)
            if( p1 == p2 ) return p1;
            
        return NULL;
    }

Log in to reply
 

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