Problem 4: Has Cycle (0pts)
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, a Link
instance, contains a cycle. Try to solve it with constant space! (i.e. no list
, dict
, set
or any other container)
Hint: use two pointers.
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 ***"