Intersection of two Linked Lists¶

1) Use a set to save node of headA¶
2) Iterate over node of headB and returns the first node that is in the set of nodes of headA¶
3) If no node of headB is in the set return None)¶
In [ ]:
def getIntersectionNode(headA: ListNode, headB: ListNode) -> Optional[ListNode]:
    s = set()
    
    # create set of node of headA
    while headA:
        s.add(headA)
        headA = headA.next
        
    # iterate of nodes of headB and return the first one that is in s
    while headB:
        if headB in s:
            return(headB)
        headB = headB.next
        
    # if no node of headB is in s then the intersection is empty
    return(None)