Simple java solution O(n) time and O(1) space


  • 0
    T
    public class Solution {
        public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            if (headA == null || headB == null)
                return null;
                
            int lenA = 0, lenB = 0;
            ListNode p1 = headA, p2 = headB;
            
            // count length for each list
            while (p1 != null) {
                lenA++;
                p1 = p1.next;
            }
            
            while (p2 != null) {
                lenB++;
                p2 = p2.next;
            }
            
            // skip longer list by diff nodes
            int diff = Math.abs(lenA - lenB);
            p1 = lenA > lenB ? headA : headB;
            
            while (diff-- > 0)
                p1 = p1.next;
                
            p2 = lenA > lenB ? headB : headA;
            
            // compare two lists with equal length
            while (p1 != null && p2 != null) {
                if (p1 == p2)
                    return p1;
                
                p1 = p1.next;
                p2 = p2.next;
            }
            
            return null;
        }
    }

  • 0
    H

    How about if headA and headB have the same length and the same length before the intersection?


Log in to reply
 

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