-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathdetect_loop.py
111 lines (92 loc) · 2.55 KB
/
detect_loop.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
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
"""
https://practice.geeksforgeeks.org/problems/detect-loop-in-linked-list/1
Given a linked list, check if the the linked list has a loop. Linked list can contain self loop.
Input:
In this problem, method takes one argument: the head of the linked list. The function should not read any input from stdin/console.
The node structure has a data part which stores the data and a next pointer which points to the next element of the linked list.
There are multiple test cases. For each test case, this method will be called individually.
Output:
Return 1 if linked list has a loop else 0.
Constraints:
1<=T<=50
1<=N<=300
Example:
Input:
2
3
1 3 4
2
4
1 8 3 4
0
Output:
True
False
"""
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# Function to insert a new node at the beginning
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# Utility function to prit the linked LinkedList
def printList(self, node):
temp = node
while (temp):
print(temp.data, end=" ")
temp = temp.next
def getHead(self):
return self.head
def createLoop(self, n):
if n == 0:
return None
temp = self.head
ptr = self.head
cnt = 1
while (cnt != n):
ptr = ptr.next
cnt += 1
# print ptr.data
while (temp.next):
temp = temp.next
temp.next = ptr
''' Please note that it's Function problem i.e.
you need to write your solution in the form of Function(s) only.
Driver Code to call/invoke your function is mentioned above. '''
# Your task is to complete this function
# Functioon should return 1/0 or True/False
def detectLoop(head):
node1 = head
node2 = head.next
while(node1 and node2):
if node1 == node2:
return True
node1 = node1.next
if node2.next == None:
return False
node2 = node2.next.next
return False
# code here
# Driver program
if __name__ == '__main__':
t = int(input())
for i in range(t):
n = int(input())
arr = list(map(int, input().strip().split()))
lst = LinkedList()
for i in arr:
lst.push(i)
ele = int(input())
lst.createLoop(ele)
if detectLoop(lst.getHead()):
print(True)
else:
print(False)
# Contributed By: Harshit Sidhwa