C++ solution,32ms and O(1)space


  • 0
    1
    class Solution {
    public:
        ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
            ListNode* p1=headA;ListNode* p2=headB;int lenA=0,lenB=0;
            while(p1!=NULL){lenA++;p1=p1->next;}
            while(p2!=NULL){lenB++;p2=p2->next;}
            if(lenA<lenB){p1=headB;p2=headA;int t=lenA;lenA=lenB;lenB=t;}
            else {p1=headA;p2=headB;}
            for(int i=0;i<lenA-lenB;i++)
                p1=p1->next;
            ListNode* res=NULL;bool isequal=0;
            for(int i=0;i<lenB;i++)
            {
                if(p1->val==p2->val)
                {
                    if(!isequal){res=p1;isequal=1;}
                   
                }
                else isequal=0;
                p1=p1->next;p2=p2->next;    
            }
            return res;
        }
       
    };

Log in to reply
 

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