August 25, 2019

160. Intersection of Two Linked Lists

160. Intersection of Two Linked Lists

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        
        if (headA == null || headB == null) {
            return null;
        }
        
        ListNode curA = headA;
        ListNode curB = headB;

        while (curA != curB) {
            
            curA = curA == null ? headB : curA.next;
            curB = curB == null ? headA : curB.next;
            
        }

        return curA;
    }
}
comments powered by Disqus