-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdetectLoop.py
More file actions
62 lines (55 loc) · 1.39 KB
/
detectLoop.py
File metadata and controls
62 lines (55 loc) · 1.39 KB
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
class Node:
def __init__(self,data):
self.data=data
self.next=None
class LinkedList:
def __init__(self):
self.head=None
def insertBeg(self,key):
newNode=Node(key)
newNode.next=self.head
self.head=newNode
def detectLoop(self):
s=[]
temp=self.head
while(temp):
if temp in s:
return True
else:
s.append(temp)
temp=temp.next
return False
llist=LinkedList()
llist.insertBeg(20)
llist.insertBeg(4)
llist.insertBeg(15)
llist.insertBeg(10)
#llist.head.next = llist.head
if( llist.detectLoop()):
print ("Loop found")
else :
print ("No Loop ")
#using Floyd's cycle-Finding algorithm
class LinkedList2:
def __init__(self):
self.head=None
def insertBeg(self,key):
newNode=Node(key)
newNode.next=self.head
self.head=newNode
def detectLoop(self):
slow_p=self.head
fast_p=self.head
while(slow_p and fast_p and fast_p.next):
slow_p=slow_p.next
fast_p=fast_p.next.next
if slow_p==fast_p:
print("Loop Found")
return
print("Loop not found")
llist=LinkedList2()
llist.insertBeg(20)
llist.insertBeg(4)
llist.insertBeg(15)
llist.insertBeg(10)
llist.detectLoop()