educative.io

Educative

Detect cycles in linked lists

Hi there,
Here is my code that works on my machine but seems not to work when posted here:

def detect_loop(lst):
    current = lst.get_head()
    head = current
    while current:
        if current.next_element == head:
            return True
        current = current.next_element
    return False 

not sure why this isn’t working…any idea?


Course: Educative: Interactive Courses for Software Developers
Lesson: Educative: Interactive Courses for Software Developers

The reason is that you find a cycle that will always have head node in it but it’s not necessary, a cycle can also appear on any other nodes that may not include head node in it.