An accepted C++ solution


  • 1
    M
    class Solution {
    public:
        ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
            if(headA==NULL||headB==NULL)
                return NULL;
            int lenA=LinkLen(headA);
            int lenB=LinkLen(headB);
            if(lenA>lenB)
            {
                for(int i=0;i<lenA-lenB;i++)
                    headA=headA->next;
            }
            else
            {
                for(int i=0;i<lenB-lenA;i++)
                    headB=headB->next;
            }
            while(headA&&headB)
            {
                if(headA==headB)
                    return headA;
                headA=headA->next;
                headB=headB->next;
            }
            return NULL;
        }
        
        int LinkLen(ListNode *head)
        {
            int tmp=0;
            while(head)
            {
                tmp++;
                head=head->next;
            }
            return tmp;
        }
        
    };

Log in to reply
 

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