Skip to content

Commit b3e34e2

Browse files
Merge pull request #452 from kiss-me1997/master
Detect loop in a linked list
2 parents c022464 + 44d222a commit b3e34e2

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

finding cycle in linked list/cycle.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
class Node:
2+
3+
# Constructor to initialize the node object
4+
def __init__(self, data):
5+
self.data = data
6+
self.next = None
7+
8+
class LinkedList:
9+
10+
# Function to initialize head
11+
def __init__(self):
12+
self.head = None
13+
14+
# Function to insert a new node at the beginning
15+
def push(self, new_data):
16+
new_node = Node(new_data)
17+
new_node.next = self.head
18+
self.head = new_node
19+
20+
# Utility function to prit the linked LinkedList
21+
def printList(self):
22+
temp = self.head
23+
while(temp):
24+
print (temp.data),
25+
temp = temp.next
26+
27+
28+
def detectLoop(self):
29+
slow_p = self.head
30+
fast_p = self.head
31+
while(slow_p and fast_p and fast_p.next):
32+
slow_p = slow_p.next
33+
fast_p = fast_p.next.next
34+
if slow_p == fast_p:
35+
print ("Found Loop")
36+
return
37+
print ("Not Found Loop")
38+
39+
# Driver program for testing
40+
llist = LinkedList()
41+
llist.push(20)
42+
llist.push(4)
43+
llist.push(15)
44+
llist.push(10)
45+
46+
# Create a loop for testing
47+
llist.head.next.next.next.next = llist.head
48+
llist.detectLoop()

0 commit comments

Comments
 (0)