Java 3ms Solution


  • 0
    X
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode currA=headA, currB=headB;
        int diff = listLen(headA)-listLen(headB);
        
        if(diff<0){
            currA = headB;
            currB = headA;
        }else{
            currA = headA;
            currB = headB;
        }
    
        diff=Math.abs(diff);
        while(currA!=null && currA!=currB){
            if(diff-->0) currA=currA.next;
            else{
                currA=currA.next;
                currB=currB.next;
            }
        }
        return currA;
    }
    
    private int listLen(ListNode node){
        int cnt=0;
        while(node!=null){
            cnt++;
            node=node.next;
        }
        return cnt;
    }

Log in to reply
 

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