Question on Intersection of Two Linked Lists


  • 0
    S

    Can anyone help me to figure out where is wrong?

    Last executed input: No intersection: {1,3,5,7,9,11,13,15,17,19,21}, {2}
    Run time error..

    thanks

    class Solution {
    public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        // first check the length of the 2 list.
        // then, start form the begining of the shorter list, 
        // and start form the delta_length + beginging of the longer list
        int lenA, lenB, swLen;
        ListNode *a, *b;
        
        if((NULL==headA)||(NULL==headB)){
            return NULL;
        }
        
        a = headA;
        lenA = 0;
        while(a){
            a=a->next;
            ++lenA;
        }
        
        b = headB;
        lenB = 0;
        while(b){
            b=b->next;
            ++lenB;
        }
        
        //make a longer than b
        if(lenA>lenB){
            int i;
            for (i=0;i<(lenA-lenB);++i){
                a=a->next;
            }
        }
        else{
            int i;
            for (i=0;i<(lenB-lenA);++i){
                b=b->next;
            }
        }
        
        
       do{
            if(a==b){
                break;   // find the insert node
            }
            a=a->next;
            b=b->next;
        }while(a&&b);
        
        return a;        // no shared node
        
    }
    };

  • 0

    Could you please at least format your code properly? Thanks.


  • 0
    S

    Hi, the code is updated, sorry for the inconvenience.


  • 0
    S

    // here, a and b are both NULL..

    //make a longer than b
    if(lenA>lenB){
    }
    

    problem solved, thanks cao bo


Log in to reply
 

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