Sharing my 52ms C++ solution


  • 0
    T
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
     
    class Solution {
    private:
        int LengthOfLinkedList(ListNode *head)
        {
            ListNode* p = head;
            int result = 0;
            while(p)
            {
                result++;
                p = p->next;
            }
            return result;
        };
        
    public:
        ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
            int nA = LengthOfLinkedList(headA);
            int nB = LengthOfLinkedList(headB);
            ListNode *pA = headA;
            ListNode *pB = headB;
            
            int i;
            if(nA > nB)
            {
                for(i=0; i<(nA-nB); i++)
                    pA = pA->next;
            }
            else
            {
                for(i=0; i<(nB-nA); i++)
                    pB = pB->next;
            }
            
            for(i=0; i<min(nA, nB); i++)
            {
                if(pA == pB)
                    return pA;
                pA = pA->next;
                pB = pB->next;
            }
                    
            return NULL;
        }
    };

Log in to reply
 

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