Wednesday, June 27, 2018

[2018-Interview] Intersection of Two Linked Lists

Original question:
https://leetcode.com/problems/intersection-of-two-linked-lists/description/


My answer:


/**
 * 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) {
        // the core logic is to find length diff between headA and headB
        // assuming headA has N more elements than headB does
        // then move node currentB from beginning of headB and the currentA node from Nth element of headA
        if (headA == null || headB == null) {
            return null;
        }
        if (headA == headB) {
            return headA;
        }
        ListNode currentA = headA;
        ListNode currentB = headB;
        ListNode endA = null;
        ListNode endB = null;
        
        while (true) {
            if (currentB == null) {
                currentB = headA;
            }
            if (currentA == null) {
                currentA = headB;
            }
            
            if (currentA.next == null) {
                endA = currentA;
            }

            if (currentB.next == null) {
                endB = currentB;
            }

            if (endA != null && endB != null && endA != endB) {
                return null;
            }

            if (currentA == currentB) {
                return currentA;
            }
            
            currentA = currentA.next;
            currentB = currentB.next;
        }
    }
}

No comments:

Post a Comment