Exemplo n.º 1
0
    Return node where the loop starts
    """
    # Approach: Add nodes to hash table. If a node already exists in table,
    #   then loop begins at that node--O(n)
    nodeSet = set()
    curNode = circularSLL.head
    while curNode != None:
        if curNode in nodeSet:
            return curNode
        else:
            nodeSet.add(curNode)
        curNode = curNode.next

    return None


# Test cases
n2 = Node('B')
n3 = Node('C')
n4 = Node('D')
n5 = Node('E')

sll = createSinglyLinkedList('A')
appendToSinglyLinkedList(sll, n2)
appendToSinglyLinkedList(sll, n3)
appendToSinglyLinkedList(sll, n4)
appendToSinglyLinkedList(sll, n5)
appendToSinglyLinkedList(sll, n3)  # Loop here. Ans: 'C' (n3)

print(loopDetection(sll))
Exemplo n.º 2
0
    while curNode != None:
        # If already in set, then the 2 lists intersect at curNode
        if curNode in nodeSet:
            return curNode
        else:
            nodeSet.add(curNode)
        curNode = curNode.next

    # No intersection
    return None


# Test cases
a1, a2 = [1, 2, 3], [4, 5]

# Create singly linked lists for testing
sll1 = createSinglyLinkedList(a1)
sll2 = createSinglyLinkedList(a2)

# Intersecting case: Add common node(s) to both lists. Ans: 100
n = Node(100)
# Non-intersecting case Ans: None
appendToSinglyLinkedList(sll1, n)
appendToSinglyLinkedList(sll2, n)

res = intersection(sll1, sll2)
if res != None:
    print(sll1, "and", sll2, "intersect at", res)
else:
    print("No intersection")