Skip to content

Commit 977a381

Browse files
committedFeb 21, 2022
Add Cycle Detection.py
1 parent 8e682c6 commit 977a381

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
#!/bin/python3
2+
3+
import os
4+
5+
6+
class SinglyLinkedListNode:
7+
def __init__(self, node_data):
8+
self.data = node_data
9+
self.next = None
10+
11+
12+
class SinglyLinkedList:
13+
def __init__(self):
14+
self.head = None
15+
self.tail = None
16+
17+
def insert_node(self, node_data):
18+
node = SinglyLinkedListNode(node_data)
19+
20+
if not self.head:
21+
self.head = node
22+
else:
23+
self.tail.next = node
24+
25+
self.tail = node
26+
27+
28+
def print_singly_linked_list(node, sep, fptr):
29+
while node:
30+
fptr.write(str(node.data))
31+
32+
node = node.next
33+
34+
if node:
35+
fptr.write(sep)
36+
37+
38+
# Complete the has_cycle function below.
39+
40+
#
41+
# For your reference:
42+
#
43+
# SinglyLinkedListNode:
44+
# int data
45+
# SinglyLinkedListNode next
46+
#
47+
#
48+
def has_cycle(head):
49+
visited = set()
50+
f = head
51+
while f:
52+
i = id(f)
53+
if i in visited:
54+
return 1
55+
visited.add(i)
56+
f = f.next
57+
return 0
58+
59+
60+
if __name__ == '__main__':
61+
fptr = open(os.environ['OUTPUT_PATH'], 'w')
62+
63+
tests = int(input())
64+
65+
for tests_itr in range(tests):
66+
index = int(input())
67+
68+
llist_count = int(input())
69+
70+
llist = SinglyLinkedList()
71+
72+
for _ in range(llist_count):
73+
llist_item = int(input())
74+
llist.insert_node(llist_item)
75+
76+
extra = SinglyLinkedListNode(-1);
77+
temp = llist.head;
78+
79+
for i in range(llist_count):
80+
if i == index:
81+
extra = temp
82+
83+
if i != llist_count - 1:
84+
temp = temp.next
85+
86+
temp.next = extra
87+
88+
result = has_cycle(llist.head)
89+
90+
fptr.write(str(int(result)) + '\n')
91+
92+
fptr.close()

0 commit comments

Comments
 (0)
Please sign in to comment.