-
Notifications
You must be signed in to change notification settings - Fork 0
/
containsCycle.py
119 lines (86 loc) · 2.93 KB
/
containsCycle.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import unittest
#def contains_cycle(firstNode):
def contains_cycle_twoPointer(firstNode):
# Check if the linked list contains a cycle
# two pointerMethod
if firstNode == None :
return False
first = firstNode
second = firstNode.next
if second == None :
return False
while not( second.next == None) :
if first.value == second.value :
return True
else:
first = first.next
if not(second.next == None) :
second = second.next.next
else:
return False
return False
#def contains_cycle_Map(firstNode):
def contains_cycle(firstNode):
nodes = []
first = firstNode
if first == None :
return False
while first.next is not None:
if first.value in nodes:
return True
else:
nodes.append(first.value)
first = first.next
return False
# Tests
class Test(unittest.TestCase):
class LinkedListNode(object):
def __init__(self, value, next=None):
self.value = value
self.next = next
def test_linked_list_with_no_cycle(self):
fourth = Test.LinkedListNode(4)
third = Test.LinkedListNode(3, fourth)
second = Test.LinkedListNode(2, third)
first = Test.LinkedListNode(1, second)
result = contains_cycle(first)
self.assertFalse(result)
def test_cycle_loops_to_beginning(self):
fourth = Test.LinkedListNode(4)
third = Test.LinkedListNode(3, fourth)
second = Test.LinkedListNode(2, third)
first = Test.LinkedListNode(1, second)
fourth.next = first
result = contains_cycle(first)
self.assertTrue(result)
def test_cycle_loops_to_middle(self):
fifth = Test.LinkedListNode(5)
fourth = Test.LinkedListNode(4, fifth)
third = Test.LinkedListNode(3, fourth)
second = Test.LinkedListNode(2, third)
first = Test.LinkedListNode(1, second)
fifth.next = third
result = contains_cycle(first)
self.assertTrue(result)
def test_two_node_cyle_at_end(self):
fifth = Test.LinkedListNode(5)
fourth = Test.LinkedListNode(4, fifth)
third = Test.LinkedListNode(3, fourth)
second = Test.LinkedListNode(2, third)
first = Test.LinkedListNode(1, second)
fifth.next = fourth
result = contains_cycle(first)
self.assertTrue(result)
def test_empty_list(self):
result = contains_cycle(None)
self.assertFalse(result)
def test_one_element_linked_list_no_cycle(self):
first = Test.LinkedListNode(1)
result = contains_cycle(first)
self.assertFalse(result)
def test_one_element_linked_list_cycle(self):
first = Test.LinkedListNode(1)
first.next = first
result = contains_cycle(first)
self.assertTrue(result)
unittest.main(verbosity=2)