LeetCode – 160. Intersection of Two Linked Lists

題目連結: https://leetcode.com/problems/intersection-of-two-linked-lists/

Hint: 透過讓兩個指向不同linked lists的pointer最終走的長度是相等的技巧,來判斷兩個linked lists是否有intersection node

    func getIntersectionNode(_ headA: ListNode?, _ headB: ListNode?) -> ListNode? {
        if headA == nil || headB == nil { return nil }
        var ptrA = headA
        var ptrB = headB
        while ptrA !== ptrB {
            ptrA = (ptrA == nil) ? headB : ptrA?.next
            ptrB = (ptrB == nil) ? headA : ptrB?.next
        }
        return ptrA
    }

Ref:

https://www.cnblogs.com/grandyang/p/4128461.html