-
Notifications
You must be signed in to change notification settings - Fork 19
/
2.8-Loop_Detection.py
58 lines (46 loc) · 1.27 KB
/
2.8-Loop_Detection.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
# CTCI 2.8
# Loop Detection
import unittest
#from LinkedList import LinkedList
# My Solution
def detect_cycle(head):
nodes = []
curr = head
while curr:
if curr in nodes:
return curr
nodes.append(curr)
curr = curr.next
return None
#-------------------------------------------------------------------------------
# CTCI Solution
def loop_detection(ll):
fast = slow = ll.head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast is slow:
break
if fast is None or fast.next is None:
return None
slow = ll.head
while fast is not slow:
fast = fast.next
slow = slow.next
return fast
#-------------------------------------------------------------------------------
#Testing
class Node():
def __init__(self, data, next=None):
self.data, self.next = data, next
class Test(unittest.TestCase):
def test_detect_cycle(self):
head1 = Node(100,Node(200,Node(300)))
self.assertEqual(detect_cycle(head1), None)
node1 = Node(600)
node2 = Node(700,Node(800,Node(900,node1)))
node1.next = node2
head2 = Node(500,node1)
self.assertEqual(detect_cycle(head2), node1)
if __name__ == "__main__":
unittest.main()