Java solution, O(m+n), without comments, but I hope it easy to understand


  • 0
        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            ListNode pa = headA, pb = headB;
            int alen = 0, blen = 0;
            while (pa != null) {
            	pa = pa.next;
            	alen++;
            }
            while (pb != null) {
            	pb = pb.next;
            	blen++;
            }
            pa = headA;
            pb = headB;
            while (alen > blen) { pa = pa.next; alen--; }
            while (blen > alen) { pb = pb.next; blen--; }
            while (pa != pb) { pa = pa.next; pb = pb.next; }
            return pa;
        }
    

Log in to reply
 

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