Skip to content

Instantly share code, notes, and snippets.

@akost
Last active June 20, 2018 09:03

Revisions

  1. akost revised this gist Jul 2, 2017. 1 changed file with 42 additions and 4 deletions.
    46 changes: 42 additions & 4 deletions cycle_detection.py
    Original file line number Diff line number Diff line change
    @@ -1,13 +1,23 @@
    """
    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:
    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:
    @@ -25,6 +35,34 @@ def has_cycle(head):

    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()
  2. akost renamed this gist Jul 2, 2017. 1 changed file with 3 additions and 2 deletions.
    5 changes: 3 additions & 2 deletions cycle_detectipn.py → cycle_detection.py
    Original file line number Diff line number Diff line change
    @@ -20,10 +20,11 @@ def has_cycle(head):
    if hare.next == None:
    return False

    if tortoise == hare.next:
    if tortoise == hare.next or tortoise == hare.next.next:
    return True

    tortoise = tortoise.next
    hare = hare.next.next

    return False
    return False

  3. akost created this gist Jul 2, 2017.
    29 changes: 29 additions & 0 deletions cycle_detectipn.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    """
    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