My solution but a little complex


  • 0
    V
    class Solution {
    public:
        ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
            if( !headA || !headB )
                return nullptr;
            
            ListNode *moveA = headA;
            ListNode *moveB = headB;
        
            int lenA = 0;
            while( moveA )
            {
                lenA++;
                moveA = moveA->next;
            }
        
            int lenB = 0;
            while( moveB )
            {
                lenB++;
                moveB = moveB->next;
            }
        
            moveA = headA;
            moveB = headB;
            if( lenA > lenB )
                for( int i = 0; i < lenA - lenB; i++ )
                    moveA = moveA->next;
        
            else if( lenA < lenB )
                for( int i = 0; i < lenB - lenA; i++ )
                    moveB = moveB->next;
                
                
            while( moveA )
                if( moveA == moveB )
                    return moveA;
                else
                {
                    moveA = moveA->next;
                    moveB = moveB->next;
                }
            
            return nullptr;
        }
    };

Log in to reply
 

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