mirror of
https://github.com/jlengrand/Coding4Interviews.git
synced 2026-03-10 08:11:24 +00:00
Implements a loop detection method
This commit is contained in:
@@ -173,6 +173,25 @@ class SingleLinkedList():
|
||||
else: # not duplicate
|
||||
element = element.nexti
|
||||
|
||||
def detect_loop(self):
|
||||
"""
|
||||
Returns True if a loop is found in a Linked List
|
||||
"""
|
||||
max_ite = self._size + 1
|
||||
# We basically keep going forward.
|
||||
# If we iterate for more than the size of the list without reaching the end,
|
||||
# we assume there is a loop somewhere.
|
||||
item = self._root
|
||||
ptr = 0
|
||||
while(ptr < max_ite):
|
||||
if item is None :
|
||||
return False
|
||||
else:
|
||||
item = item.nexti
|
||||
ptr += 1
|
||||
return True
|
||||
|
||||
|
||||
def __len__(self):
|
||||
# Returns the number of elements in the list
|
||||
return self._size
|
||||
|
||||
@@ -20,7 +20,7 @@ class test_single_linked_list_item(unittest.TestCase):
|
||||
|
||||
def test_has_next(self):
|
||||
a = 12
|
||||
t = SingleListItem(12)
|
||||
t = SingleListItem(a)
|
||||
|
||||
self.assertEqual(False, t.has_next())
|
||||
|
||||
@@ -184,5 +184,23 @@ class test_single_linked_list(unittest.TestCase):
|
||||
self.assertEqual(3, len(sl))
|
||||
self.assertEqual("2, 1, 3", sl.__str__())
|
||||
|
||||
def test_detect_loop(self):
|
||||
|
||||
sl = SingleLinkedList()
|
||||
|
||||
sl.add(2)
|
||||
sl.add(1)
|
||||
sl.add(3)
|
||||
sl.add(2)
|
||||
sl.add(3)
|
||||
sl.add(1)
|
||||
sl.add(2)
|
||||
|
||||
self.assertEqual(7, len(sl))
|
||||
self.assertEqual(False, sl.detect_loop())
|
||||
|
||||
sl._root.nexti.nexti.nexti.nexti = sl._root
|
||||
self.assertEqual(True, sl.detect_loop())
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
Reference in New Issue
Block a user