Javascript solution (Beats 98%)


  • 0
    R
    var getIntersectionNode = function(headA, headB) {
        var lengthA = linkedListLength(headA),
            lengthB = linkedListLength(headB),
            diference = lengthA - lengthB;
        
        if(diference < 0){
            var temp = headA;
            headA = headB;
            headB = temp;
            diference *= -1;
        }
        
        for(var i = 0; i < diference; i++){
            headA = headA.next;
        }
        
        while(headA !== null && headB !== null){
            if(headA === headB){
                return headA;
            }
            
            headA = headA.next;
            headB = headB.next;
        }
        
        return null;
        
    };
    
    var linkedListLength = function(head){
        var count = 0;
        
        while(head !== null){
            count++;
            head = head.next;
        }
        
        return count;
    };
    

Log in to reply
 

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