Last active
June 20, 2018 09:03
-
-
Save akost/2fd9e552be4e30803bc91c8d65f0dcb3 to your computer and use it in GitHub Desktop.
Linked list cycle detection. Python solution for https://www.hackerrank.com/challenges/detect-whether-a-linked-list-contains-a-cycle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Detect a cycle in a linked list. Note that the head pointer may be 'None' if the list is empty. | |
A Node is defined as: | |
class Node(object): | |
def __init__(self, data = None, next_node = None): | |
self.data = data | |
self.next = next_node | |
""" | |
def has_cycle(head): | |
if head == None: | |
return False | |
tortoise = hare = head | |
while(tortoise or hare or hare.next): | |
if hare.next == None: | |
return False | |
if tortoise == hare.next: | |
return True | |
tortoise = tortoise.next | |
hare = hare.next.next | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment