Skip to content

Problem 4: Has Cycle (0pts)

Problem

The Link class can represent lists with cycles. That is, a list may contain itself as a sublist. Implement has_cycle that returns whether its argument lnk, a Link instance, contains a cycle. Try to solve it with constant space! (i.e. no list, dict, set or any other container)

Link 类可以表示带有循环的列表。即,一个列表可能包含自身作为子列表。实现 has_cycle,它返回其参数 lnk(一个 Link 实例)是否包含循环。尝试用常量空间解决它!(即不使用 listdictset 或任何其他容器)

def has_cycle(lnk):
    """ Returns whether `lnk` has cycle.

    >>> lnk = Link(1, Link(2, Link(3)))
    >>> has_cycle(lnk)
    False
    >>> lnk.rest.rest.rest = lnk
    >>> has_cycle(lnk)
    True
    >>> lnk.rest.rest.rest = lnk.rest
    >>> has_cycle(lnk)
    True
    """
    "*** YOUR CODE HERE ***"