Detect Cycle in a Linked List using Map Last Updated : 18 Jul, 2024 Comments Improve Suggest changes Like Article Like Report Given a Linked List, check if the linked list has a loop or not.There are various methods shown here: Detect Cycle in Linked ListExample Input: 20->4->54->6->NULL Output: No loop is detected. Explanation: While traversing the linked list, we reach the end of the linked list. Therefore, no loop is present in the linked list.Input: 20->4->5->10->20 Output: Loop detected. Explanation: While traversing the linked list, reaching the node with value 10, it is linked with the head node, which depicts a loop in the linked list. Therefore, a loop is present in the linked list. Approach:Create a map that will store the visited node in the linked list.Traverse the linked list and do the following: Check whether the current node is present on the map or not.If the current node is not present in the map then, insert the current node into the map.If the Node is present in the map, the loop in a linked list is detected.If we reach the Null Node while traversing the linked list then, the given linked list has no loop present in it.Below is the implementation of the above approach: C++ // C++ program to detect loop in // given linked list using map #include <bits/stdc++.h> using namespace std; // Structure for a node in Linked List struct Node { int data; Node* next; }; // Function to create Linked List // Node Node* newNode(int d) { Node* temp = new Node; temp->data = d; temp->next = NULL; return temp; } // Declaration of Map to keep // mark of visited Node map<Node*, bool> vis; bool flag = 0; // Function to check cycle in Linked // List void check(Node* head) { // If head is NULL return ; if (head == NULL) { flag = 0; return; } // Mark the incoming Node as // visited if it is not visited yet if (!vis[head]) { vis[head] = true; check(head->next); } // If a visited Node is found // Update the flag value to 1 // and return ; else { flag = 1; return; } } // Driver Code int main() { // Create a head Node Node* head = newNode(20); // Inserting Node in Linked List head->next = newNode(4); head->next->next = newNode(5); head->next->next->next = newNode(10); // Just to make a cycle head->next->next->next->next = head; // Function that detect cycle in // Linked List check(head); // If flag is true, loop is found if (flag) cout << "Loop detected."; // If flag is false, No Loop // detected else cout << "No Loop Found."; cout << endl; return 0; } Java // Java program to detect loop in // given linked list using map import java.util.*; class GFG{ // Structure for a node in Linked List static class Node { int data; Node next; }; // Function to create Linked List // Node static Node newNode(int d) { Node temp = new Node(); temp.data = d; temp.next = null; return temp; } // Declaration of Map to keep // mark of visited Node static HashMap<Node, Boolean> vis = new HashMap<>(); static boolean flag = false; // Function to check cycle in Linked // List static void check(Node head) { // If head is null return ; if (head == null) { flag = false; return; } // Mark the incoming Node as // visited if it is not visited yet if (!vis.containsKey(head)) { vis.put(head, true); check(head.next); } // If a visited Node is found // Update the flag value to 1 // and return ; else { flag = true; return; } } // Driver Code public static void main(String[] args) { // Create a head Node Node head = newNode(20); // Inserting Node in Linked List head.next = newNode(4); head.next.next = newNode(5); head.next.next.next = newNode(10); // Just to make a cycle head.next.next.next.next = head; // Function that detect cycle in // Linked List check(head); // If flag is true, loop is found if (flag) System.out.print("Loop detected."); // If flag is false, No Loop // detected else System.out.print("No Loop Found."); System.out.println(); } } // This code is contributed by Rajput-Ji Python # Python3 program to detect loop in # given linked list using map # Structure for a node in Linked List class Node: def __init__(self, val): self.data = val self.Next = None # Function to create Linked List Node def newNode(d): temp = Node(d) return temp # Declaration of Map to keep # mark of visited Node vis = {} flag = False # Function to check cycle in Linked # List def check(head): global vis, flag # If head is null return ; if head == None: flag = False return # Mark the incoming Node as # visited if it is not visited yet if head not in vis: vis[head] = True check(head.Next) # If a visited Node is found # Update the flag value to 1 # and return ; else: flag = True return # Create a head Node head = newNode(20) # Inserting Node in Linked List head.Next = newNode(4) head.Next.Next = newNode(5) head.Next.Next.Next = newNode(10) # Just to make a cycle head.Next.Next.Next.Next = head # Function that detect cycle in # Linked List check(head) # If flag is true, loop is found if flag: print("Loop detected.") # If flag is false, No Loop # detected else: print("No Loop Found.") # This code is contributed by suresh07. C# // C# program to detect loop in // given linked list using map using System; using System.Collections.Generic; class GFG{ // Structure for a node in Linked List public class Node { public int data; public Node next; }; // Function to create Linked List // Node static Node newNode(int d) { Node temp = new Node(); temp.data = d; temp.next = null; return temp; } // Declaration of Map to keep // mark of visited Node static Dictionary<Node, Boolean> vis = new Dictionary<Node, Boolean>(); static bool flag = false; // Function to check cycle in Linked // List static void check(Node head) { // If head is null return ; if (head == null) { flag = false; return; } // Mark the incoming Node as // visited if it is not visited yet if (!vis.ContainsKey(head)) { vis.Add(head, true); check(head.next); } // If a visited Node is found // Update the flag value to 1 // and return ; else { flag = true; return; } } // Driver Code public static void Main(String[] args) { // Create a head Node Node head = newNode(20); // Inserting Node in Linked List head.next = newNode(4); head.next.next = newNode(5); head.next.next.next = newNode(10); // Just to make a cycle head.next.next.next.next = head; // Function that detect cycle in // Linked List check(head); // If flag is true, loop is found if (flag) Console.Write("Loop detected."); // If flag is false, No Loop // detected else Console.Write("No Loop Found."); Console.WriteLine(); } } // This code is contributed by gauravrajput1 JavaScript <script> // javascript program to detect loop in // given linked list using map // Structure for a node in Linked List class Node { constructor(val) { this.data = val; this.next = null; } } // Function to create Linked List // Node function newNode(d) { var temp = new Node(); temp.data = d; temp.next = null; return temp; } // Declaration of Map to keep // mark of visited Node var vis = new Map();; var flag = false; // Function to check cycle in Linked // List function check(head) { // If head is null return ; if (head == null) { flag = false; return; } // Mark the incoming Node as // visited if it is not visited yet if (!vis.has(head)) { vis.set(head, true); check(head.next); } // If a visited Node is found // Update the flag value to 1 // and return ; else { flag = true; return; } } // Driver Code // Create a head Node var head = newNode(20); // Inserting Node in Linked List head.next = newNode(4); head.next.next = newNode(5); head.next.next.next = newNode(10); // Just to make a cycle head.next.next.next.next = head; // Function that detect cycle in // Linked List check(head); // If flag is true, loop is found if (flag) document.write("Loop detected."); // If flag is false, No Loop // detected else document.write("No Loop Found."); document.write(); // This code contributed by Rajput-Ji </script> OutputLoop detected.Time Complexity: O(N) Auxiliary Space: O(N) Comment More infoAdvertise with us Next Article Detect Cycle in a Linked List using Map V VikasVishwakarma1 Follow Improve Article Tags : Linked List Algorithms Recursion DSA Linked Lists +1 More Practice Tags : AlgorithmsLinked ListRecursion Similar Reads Detect Loop or Cycle in Linked List Given a singly linked list, check if the linked list has a loop (cycle) or not. A loop means that the last node of the linked list is connected back to a node in the same list.Examples:Input: head: 1 -> 3 -> 4 -> 3Output: true Input: head: 1 -> 8 -> 3 -> 4 -> NULL Output: false 10 min read Detect and Remove Loop in Linked List Given the head of a linked list that may contain a loop. A loop means that the last node of the linked list is connected back to a node in the same list. The task is to remove the loop from the linked list (if it exists).Example:Input: Output: 1 -> 3 -> 4 Explanation: The Loop is removed from 15 min read Searching in Circular Linked list Given a Circular Linked List CList, and an element K, the task is to check if this element K is present in the Circular Linked list or not. Example: Input: CList = 6->5->4->3->2, K = 3 Output: Found Input: CList = 6->5->4->3->2, K = 1 Output: Not Found Approach: The approach 7 min read Count minimum frequency elements in a linked list Given a linked list containing duplicate elements. The task is to find the count of all minimum occurring elements in the given linked list. That is the count of all such elements whose frequency is minimum in the matrix. Examples: Input : 1-> 2-> 2-> 3 Output : 2 Explanation: 1 and 3 are e 8 min read Delete a Linked List node at a given position Given a singly linked list and a position (1-based indexing), the task is to delete a linked list node at the given position.Note: Position will be valid (i.e, 1 <= position <= linked list length)Example: Input: position = 2, Linked List = 8->2->3->1->7Output: Linked List = 8->3 8 min read Check if elements of Linked List are present in pair Given a singly linked list of integers. The task is to check if each element in the linked list is present in a pair i.e. all elements occur even no. of times.Examples: Input: 1 -> 2 -> 3 -> 3 -> 1 -> 2Output: YesInput: 10 -> 20 -> 30 -> 20Output: NoMethod : Using MapWe will 5 min read First non-repeating in a linked list Given a linked list, find its first non-repeating integer element. Examples: Input : 10->20->30->10->20->40->30->NULLOutput :First Non-repeating element is 40.Input :1->1->2->2->3->4->3->4->5->NULLOutput :First Non-repeating element is 5.Input :1->1 12 min read Find length of loop/cycle in given Linked List Given the head of a linked list. The task is to find the length of the loop in the linked list. If the loop is not present return 0.Examples:Input: head: 1 â 2 â 3 â 4 â 5 â 2Output: 4Explanation: There exists a loop in the linked list and the length of the loop is 4. Input: head: 25 â 14 â 19 â 33 12 min read Count Occurrences in a Linked List Given a singly linked list and a key, the task is to count the number of occurrences of the given key in the linked list. Example : Input : head: 1->2->1->2->1->3->1 , key = 1Output : 4 Explanation: key equals 1 has 4 occurrences.Input : head: 1->2->1->2->1, key = 3Outp 9 min read Search an element in a Doubly Linked List Given a Doubly linked list(DLL) containing n nodes and an integer x, the task is to find the position of the integer x in the doubly linked list. If no such position found then print -1.Examples:Input: Linked List = 18 <-> 15 <-> 8 <-> 9 <-> 14, x = 8 Output: 3 Explanation: x 7 min read Like