Java code: O(n )time and O(1) space


  • 1
    R

    public ListNode getIntersectionNode(ListNode l1, ListNode l2) {

        if(l1==null||l2==null)
        return null;
        
        ListNode temp1=l1;
        ListNode temp2=l2;
        int s1=0,s2=0;
        
        while(temp1!=null){
            s1++;
            temp1=temp1.next;
        }
        
        while(temp2!=null){
            s2++;
            temp2=temp2.next;
        }
        int n=Math.abs(s1-s2);
        temp1=l1;
        temp2=l2;
        ListNode temp=null;
        if(s1>s2){
        //temp1=l1;
        while(n>0){
            temp1=temp1.next;
            n--;
        }
        }
        
        else {
        //temp2=l2;
        while(n>0){
            temp2=temp2.next;
            n--;
        }
        }
        
        
        while(temp1!=null && temp2!=null){
            if(temp1==temp2)
            return temp1;
            
            temp1=temp1.next;
            temp2=temp2.next;
            
            
        }
        
        return null;
        
        
        
        
    }

  • 0
    J

    smart! makes two lists the same length, then do the comparison. it avoids using two for loops.


Log in to reply
 

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