Java Solution, O(n) time and O(1) memory.


  • 0
    public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int lA=0,lB=0;
        ListNode pA=headA, pB=headB;
        if(headA==null||headB==null)    return null;
        while(pA!=null){
            lA++;
            pA=pA.next;
        }
        while(pB!=null){
            lB++;
            pB=pB.next;
        }
        for(int i=0;i<Math.abs(lA-lB);i++){
            if(lA<lB)
                headB=headB.next;
            else 
                headA=headA.next;
        }
        while(headA!=null&&headB!=null){
            if(headA==headB) return headA;
            headA=headA.next;
            headB=headB.next;
        }
        return null;
    }
    

    }


Log in to reply
 

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