-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDetect loop in linked list.py
46 lines (38 loc) · 1.01 KB
/
Detect loop in linked list.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
class Solution:
def detectLoop(self, head):
visited = set()
while head != None:
if head in visited:
return True
visited.add(head)
head = head.next
return False
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert(self, val):
if self.head is None:
self.head = Node(val)
self.tail = self.head
else:
self.tail.next = Node(val)
self.tail = self.tail.next
def loopHere(self, pos):
if pos == 0:
return
walk = self.head
for i in range(1, pos):
walk = walk.next
self.tail.next = walk
for _ in range(int(input())):
n = int(input())
LL = LinkedList()
for i in input().split():
LL.insert(int(i))
LL.loopHere(int(input()))
print(Solution().detectLoop(LL.head))