-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2. Detect Loop in linked list - v1.py
More file actions
67 lines (55 loc) · 1.72 KB
/
2. Detect Loop in linked list - v1.py
File metadata and controls
67 lines (55 loc) · 1.72 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
63
64
65
66
67
#User function Template for python3
'''
# Node Class
class Node:
def __init__(self, data): # data -> value stored in node
self.data = data
self.next = None
'''
class Solution:
#Function to check if the linked list has a loop.
def detectLoop(self, head):
#code here
print(f"HEAD : {head}")
print(f"data : {head.__dict__}")
#print(type(head))
print(f"next : {head.next}")
print(f"data : {self.__dict__}")
#{
# Driver Code Starts
#Initial Template for Python 3
# Node Class
class Node:
def __init__(self, data): # data -> value stored in node
self.data = data
self.next = None
# Linked List Class
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
# creates a new node with given value and appends it at the end of the linked list
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
#connects last node to node at position pos from begining.
def loopHere(self,pos):
if pos==0:
return
walk = self.head
for i in range(1,pos):
walk = walk.next
self.tail.next = walk
if __name__ == '__main__':
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))
# } Driver Code Ends