Intersection of Two Linked Lists

[Question]: Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.

func getIntersectionNode(_ headA: ListNode?, _ headB: ListNode?) -> ListNode? {
     if headA == nil || headB == nil { return nil }
     var a = headA, b = headB
    // Where a & b node has same reference means it's a intersaction point
     while a !== b {
         a = a == nil ? headB : a?.next
         b = b == nil ? headA : b?.next
         // print("Dry run Value of a--", a, " Value of b ---", b)
     }
     // print("a", a, "b", b)
     return a
 }

Leave a Comment

Your email address will not be published. Required fields are marked *