Skip to content

Instantly share code, notes, and snippets.

@akost
Last active June 20, 2018 09:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akost/2fd9e552be4e30803bc91c8d65f0dcb3 to your computer and use it in GitHub Desktop.
Save akost/2fd9e552be4e30803bc91c8d65f0dcb3 to your computer and use it in GitHub Desktop.
"""
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
"""
import unittest
class Node(object):
def __init__(self, data = None, next_node = None):
self.data = data
self.next = next_node
def setNext(self, next_node = None):
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 or tortoise == hare.next.next:
return True
tortoise = tortoise.next
hare = hare.next.next
return False
class TestStringMethods(unittest.TestCase):
def test_loop_empty(self):
self.assertEqual(has_cycle(None), False)
def test_loop(self):
self.assertEqual(has_cycle(n5), True)
def test_no_loop(self):
self.assertEqual(has_cycle(m5), False)
n1 = Node(1, None)
n2 = Node(2, n1)
n3 = Node(3, n2)
n4 = Node(4, n3)
n5 = Node(5, n4)
n2.setNext(n4) # Loop
m1 = Node(1, None)
m2 = Node(2, m1)
m3 = Node(3, m2)
m4 = Node(4, m3)
m5 = Node(5, m4)
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment