-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlength_of_loop.py
106 lines (91 loc) · 2.52 KB
/
length_of_loop.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
class Node:
def __init__(self,data,next):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def append(self,data):
tmp = Node(data,None)
if self.head == None:
self.head = tmp
else:
temp = self.head
while temp.next is not None:
temp = temp.next
temp.next = tmp
def print(self):
t = self.head
while t is not None:
print(t.data)
t = t.next
def push(self,data):
tmp = Node(data,None)
tmp.next = self.head
self.head = tmp
def insert(self,index,element):
tmp = Node(element,None)
temp = self.head
while temp.data != index:
temp = temp.next
tmp.next = temp.next
temp.next = tmp
def length(self):
count = 0
temp =self.head
while temp:
count+=1
temp = temp.next
return count
def detectloop(self):
s = set()
tmp = self.head
while tmp is not None:
if tmp in s:
return True
s.add(tmp)
tmp = tmp.next
return False
def detectloop1(self):
s = set()
tmp = self.head
while tmp is not None:
if tmp in s:
return tmp
s.add(tmp)
tmp = tmp.next
return False
def length_of_loop(self):
if(self.detectloop()):
tmp = self.detectloop1()
val = tmp.data
count = 0
while tmp is not None:
if tmp is None:
return 0
count = count +1
tmp = tmp.next;
if tmp.data == val:
return count
else:
return "loop not found"
def makeloop(self,value):
l = self.head
for i in range(1,value):
l = l.next
end = self.head
while end.next is not None:
end = end.next
end.next = l
if __name__ == '__main__':
LinkedLists = LinkedList()
LinkedLists.append(10)
LinkedLists.append(20)
LinkedLists.push(40)
LinkedLists.push(60)
LinkedLists.insert(20,70)
LinkedLists.insert(10,80)
LinkedLists.insert(10,80)
LinkedLists.insert(10,80)
LinkedLists.makeloop(8)
print(LinkedLists.length_of_loop())