3/39
Part 1 of 7 · Nodes and costsLearn and do

A walk around a cycle never ends, so give every walk a limit

A list can loop back on itself, and then a walk never ends.

def values(head, limit=10_000):
    out, node = [], head
    while node is not None:
        if len(out) == limit:
            raise ValueError(f"more than {limit} nodes: a cycle, or a very long list")
        out.append(node.val)
        node = node.next
    return out


loop = Node(3, Node(1, Node(4)))
loop.next.next.next = loop.next
values(loop, limit=10)
Predict

The 4 now points back at the 1. What does values(loop, limit=10) do?

Pick one to see what it prints.
Pick an answer above to see the rest