From fec6d266070bd93289af31ed7d05f721760fa1c8 Mon Sep 17 00:00:00 2001 From: shubh_goel2002 <80595515+vader22a@users.noreply.github.com> Date: Sat, 15 Oct 2022 22:31:40 +0530 Subject: [PATCH] Create LOOP DETECTION.py Language=Python Loop Detection for Linklist. Complexity Analysis: Time complexity: O(n). Only one traversal of the loop is needed. Auxiliary Space: O(n). n is the space required to store the value in hashmap. --- LOOP DETECTION.py | 66 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 LOOP DETECTION.py diff --git a/LOOP DETECTION.py b/LOOP DETECTION.py new file mode 100644 index 0000000..9e76835 --- /dev/null +++ b/LOOP DETECTION.py @@ -0,0 +1,66 @@ +class Node: + + # Constructor to initialize + # the node object + 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 print it + # the linked LinkedList + def printList(self): + temp = self.head + while(temp): + print(temp.data, end=" ") + temp = temp.next + + def detectLoop(self): + s = set() + temp = self.head + while (temp): + + # If we already have + # this node in hashmap it + # means there is a cycle + # (Because we are encountering + # the node second time). + if (temp in s): + return True + + # If we are seeing the node for + # the first time, insert it in hash + s.add(temp) + + temp = temp.next + + return False + + +# Driver program for testing +llist = LinkedList() +llist.push(20) +llist.push(4) +llist.push(15) +llist.push(10) + +# Create a loop for testing +llist.head.next.next.next.next = llist.head + +if(llist.detectLoop()): + print("Loop found") +else: + print("No Loop ")