-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2. Detect Loop in linked list - v2 GPT.py
More file actions
76 lines (60 loc) · 1.84 KB
/
2. Detect Loop in linked list - v2 GPT.py
File metadata and controls
76 lines (60 loc) · 1.84 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
68
69
70
71
72
73
74
75
76
#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):
slow = head
fast = head
print(fast, fast.next)
print("\n")
while fast and fast.next:
print(slow.next, fast.next.next)
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
#{
# 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