×

Detect Loop in Linked List: Data Structure

Detect the Loop in Linked List: In this problem, we will be seeing some technique through which we can detect the loop in linked list. We will discuss each technique one by one.

Detect Loop in Linked List

Technique 1: Hashing method: -

In hashing method, we traverse the list one by one and we put the addresses of the node in a hash map. At any point, if we get NULL then we return false and if next of present or current node is found in hash map then we will return true.

//Implementation of above method in Java Language 
import java.util.*;
 public class ListLoopDetection {
     static Node start;  
     /* Linked list Node*/
     static class Node {
         int data;
         Node next;
         Node(int d)
         {
             data = d;
             next = null;
         }
     }
     /* Inserts a new Node into the linked list */
     static public void add(int new_data)
     {
         Node node = new Node(new_data);
          node.next = start;
         start = node;
     }
     // Function returns true if loop is in linked list
     //Else returns false.
     static boolean detectLoop(Node h)
     {
         HashMap<Node,Boolean> s = new HashMap<Node,Boolean>();
         while (h != null) {
             if (s.get(h) != null)
                 return true;
             s.put(h,true);
             h = h.next;
         }
         return false;
     }
     /* Driver function for checking the program */
     public static void main(String[] args)
     {
         LinkedList ll = new LinkedList();
         ll.add(20);
         ll.add(4);
         ll.add(15);
         ll.add(10);
         /*Create loop for testing */
         ll.start.next.next.next.next = ll.start;
         if (detectLoop(start))
             System.out.println("Loop found");
         else
             System.out.println("No Loop found");
     }
 } 

Output: -

Loop found

Complexity Analysis: -

The time complexity of this solution is O(n) and the space complexity of is O(n).

Technique 2: Floyd’s Cycle-Finding Algorithm: -This method is faster than above, in this we traverse the whole linked list using two pointers. We move the one pointer by next called slow pointer and another pointer by next to next called fast pointer. Then we will check if these two pointers meet at the same node then we can say there is a loop present in the linked list and these pointers don’t meet to each other then we can say the linked list doesn’t contain any loop.

 //Implementation of above method in C Language
 #include <stdio.h>
 #include <stdlib.h>
 /* Link list node */
 struct Node {
     int data;
     struct Node* next;
 };
 void add(struct Node** ref, int new_data)
 {
     /* allocate node */
     struct Node* node = (struct Node*)malloc(sizeof(struct Node));
     node->data = new_data;
     node->next = (*ref);
     (*ref) = node;
 }
 int detectLoop(struct Node* list)
 {
     struct Node *slow_p = list, *fast_p = list;
     while (slow_p && fast_p && fast_p->next) {
         slow_p = slow_p->next;
         fast_p = fast_p->next->next;
         if (slow_p == fast_p) {
             return 1;
         }
     }
     return 0;
 }
 /* Driver function for checking the program */
 int main()
 {
     /* Start with the empty list */
     struct Node* start = NULL;
     add(&start, 20);
     add(&start, 4);
     add(&start, 15);
     add(&start, 10);
     /* Create a loop for testing */
     start->next->next->next->next = start;
     if (detectLoop(start))
         printf("Loop found");
     else
         printf("No Loop found");
     return 0;
 } 

Output: -

Loop found

Complexity Analysis: -

The time complexity of this solution is O(n) and the space complexity of is O(1).


Related Topics

Quick Sort vs Merge Sort

In this article, we will take an overview of Quick Sort and Merge Sort and then discuss the differences between them. What is Quick Sort? Quick Sort – The idea behind the...

7 minutes read.

Cocktail Sort

C Program executes cocktail sort. Combo sort is a somewhat straightforward arranging calculation initially planned by Wlodzimierz Dobosiewicz and Artur Borowy in 1980, later rediscovered by Stephen Lacey and Richard Box...

5 minutes read.

What is an AVL Tree in Data Structure?

AVL tree stands for (Adelson, Velskii, & Landis Tree) Data structure Data management is called database management. A data model is a system used to store, manage, and optimize computer resources. Data...

4 minutes read.

Digital Search Tree in Data Structures

What is a digital search Tree in Data Structures? The Digital search tree is known for its application and diversity in the way it has impacted our world in the field...

3 minutes read.

Depth of binary tree

We all know that a binary tree is a kind of tree that helps us maintain the order and balance of the tree. It is a type of tree in...

4 minutes read.

Count pairs from two linked lists whose sum is equal to a given value

Count pairs from two linked lists whose sum is equal to a given value In this problem, we have given two linked lists of size n1 and n2 with distinct elements...

4 minutes read.

Create a binary search tree

Implementation In this section of the article, we will see the usage and mechanism of how we will create a given binary tree. Let's observe these in more depth and then...

7 minutes read.

What Is Dfs Algorithm in Data Structures

DFS stands for Depth First Search. Generally, it is a repetitive or decidable type of algorithm which is basically used in identifying all the vertices or nodes of a graph...

5 minutes read.

Heap Sort in Data Structure

Heap Sort: Heap Sort is very useful and efficient sorting algorithm in data structure. We can say it is a comparison base sorting algorithm, similar sort where we will find...

2 minutes read.

B+ Tree Program in Q language

A B+ tree is just an improvised version of a self-balancing and well-maintained tree in which all the key values that hold valuable information is present at the bottom, which...

9 minutes read.

Stack vs Array

Difference between Array and Stack In this article, we are going to discuss the major differences between the stack and array data structures: Array – In the data structure, the array is...

3 minutes read.

Binary tree insertion

As we all know, a binary tree has a maximum of two children and helps us manage the info correctly. Here the name of the tree itself portrays the mechanism...

4 minutes read.

Function to Create a Copy of Binary Search Tree

Implementation // creating a new hashmap in the language C++ that will help us clone a binary tree with arbitrary pointers.  #include<iostream> #include<unordered_map> using namespace std; /* A given binary tree has a record, a...

9 minutes read.

Binary Tree Uses

A binary tree is a tree data structure containing hubs with at most two children for instance a right and left child. The node at the top is insinuated as the...

3 minutes read.

Collision Resolution Techniques

Collision Resolution Techniques Collision in hashing In this, the hash function is used to compute the index of the array.The hash value is used to store the key in the hash table,...

2 minutes read.

Implementation of stack

Implementation of stack: The stack can be implemented in two ways: using array and using a linked list. The pop and push operations in the array are simpler than the...

3 minutes read.

Strings in Data Structures

Strings and functions in C A string is a collection of characters. We'll learn how to declare strings, operate with strings in C programming, and use pre-defined string handling routines. We'll look...

7 minutes read.

Complete Binary tree

In this article, we will discuss the complete binary tree. But before start discussing the complete binary tree, we should first see a brief description of a binary tree. What is...

7 minutes read.

What is the B+ Tree in Data Structures?

We all know that the B+ tree in data structures is nothing but just an extended version of the B tree. It allows the smooth working of all the operations...

7 minutes read.

Identical Linked Lists

Identical Linked Lists In this problem, we have given two linked lists, and we need to check whether the given linked lists are identical or not. Identical means they have the...

4 minutes read.