Detect Cycle in a Linked List using Map - GeeksforGeeks

29 Oct, 2021
Given a Linked List, check if the linked list has a loop or not.There are various methods shown here: Detect Cycle in Linked List
Example  
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.
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.
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++
Java
Python3
C#
Javascript
// C++ program to detect loop in// given linked list using map#include <bits/stdc++.h>using namespace std; // Structure for a node in Linked Liststruct Node {    int data;    Node* next;}; // Function to create Linked List// NodeNode* newNode(int d){    Node* temp = new Node;    temp->data = d;    temp->next = NULL;    return temp;} // Declaration of Map to keep// mark of visited Nodemap<Node*, bool> vis;bool flag = 0; // Function to check cycle in Linked// Listvoid 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 Codeint 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 program to detect loop in// given linked list using mapimport java.util.*; class GFG{ // Structure for a node in Linked Liststatic class Node{    int data;    Node next;}; // Function to create Linked List// Nodestatic Node newNode(int d){    Node temp = new Node();    temp.data = d;    temp.next = null;    return temp;} // Declaration of Map to keep// mark of visited Nodestatic HashMap<Node, Boolean> vis = new HashMap<>();static boolean flag = false; // Function to check cycle in Linked// Liststatic 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 Codepublic 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
# Python3 program to detect loop in# given linked list using map # Structure for a node in Linked Listclass Node:    def __init__(self, val):        self.data = val        self.Next = None # Function to create Linked List Nodedef newNode(d):    temp = Node(d)    return temp # Declaration of Map to keep# mark of visited Nodevis = {}flag = False # Function to check cycle in Linked# Listdef 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 Nodehead = newNode(20) # Inserting Node in Linked Listhead.Next = newNode(4)head.Next.Next = newNode(5)head.Next.Next.Next = newNode(10) # Just to make a cyclehead.Next.Next.Next.Next = head # Function that detect cycle in# Linked Listcheck(head) # If flag is true, loop is foundif flag:    print("Loop detected.") # If flag is false, No Loop# detectedelse:    print("No Loop Found.")         # This code is contributed by suresh07.
// C# program to detect loop in// given linked list using mapusing System;using System.Collections.Generic; class GFG{ // Structure for a node in Linked Listpublic class Node{    public int data;    public Node next;}; // Function to create Linked List// Nodestatic Node newNode(int d){    Node temp = new Node();    temp.data = d;    temp.next = null;    return temp;} // Declaration of Map to keep// mark of visited Nodestatic Dictionary<Node,                  Boolean> vis = new Dictionary<Node,                                                Boolean>();static bool flag = false; // Function to check cycle in Linked// Liststatic 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 Codepublic 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
<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>
Loop detected.
 
Time Complexity: O(N*log N) Auxiliary Space: O(N) 
Code_Mech
Rajput-Ji
GauravRajput1
suresh07
Linked Lists
Algorithms
Linked List
Recursion
Linked List
Recursion
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SCAN (Elevator) Disk Scheduling Algorithms
Program for SSTF disk scheduling algorithm
Rail Fence Cipher - Encryption and Decryption
Quadratic Probing in Hashing
Linked List | Set 1 (Introduction)
Linked List | Set 2 (Inserting a node)
Reverse a linked list
Stack Data Structure (Introduction and Program)
Linked List | Set 3 (Deleting a node)