×

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

Object-Oriented Analysis and Design

While designing a system, one should know all the requirements or needs of the plan beforehand, and to do so, we should use a systematic approach to analyze the goal...

3 minutes read.

Hash Table vs STL Map

Hash table and STL map are extremely valuable information structures in software engineering. Here we will consider the examination between their properties to be well as execution.  To start with, we will...

7 minutes read.

Finding the Minimum and Maximum Value of a Binary Tree

Implementation // Writing a C++ program that will help us find out the maximum and the minimum in a binary tree.  #include <bits/stdc++.h> #include <iostream> using namespace std; // creating a new class tree node. class...

5 minutes read.

What is the Use of Segment Trees in Data Structure?

Segment trees Segment trees are also called statistical trees in computer science. They are a type of tree data structure. Segment trees are used to store information regarding segments and intervals....

6 minutes read.

Balanced Binary Tree

A balanced binary tree is just a random nod-based tree with a rule of keeping its height minimum in size to maintain various operations such as insertions, deletions and several...

3 minutes read.

Common Operations on various Data Structures

Data structures are ways to organise data in computer memory for quick and effective use. The storage of data uses a variety of data-structures. It is also possible to define...

7 minutes read.

What is a 2-3 Tree in Data Structure?

Tree Data structure The information about the tree is self-explanatory. Trees are ordered and, therefore, not linear. But they are actually designed differently. Tree A node-based data model that represents and...

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.

Big O Notations

What is Big O Notation, and why is it important? "Big O notation is a mathematical notation that depicts a function's limiting behaviour when the input tends towards a certain value...

10 minutes read.

Flattening a Linked List

In this article, we are going to study about the logic behind the flattening of linked list and we also going to build a code in the C++ to flatten...

3 minutes read.

Bitonical Sort

Arranging an unordered collecttion of things into asignificant order. •Comparision Based Model: Bubble Sort, Selection Sort -->Non-Comparison Based. Model: Bucket Sort or on the other hand a Count Sort Bitonic Sort: Bitonic sort Algorithm was made...

5 minutes read.

Perfect Binary Tree

Complete binary trees are an important and general topic in the concept – of tree data structures. Before discussing a complete binary tree, we need to know the concept of...

4 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 Queue

Implementation of queue: We can implement the queue through the array and linked list. An array is the easiest way to implement the queue. When a queue is created with the...

7 minutes read.

Difference between Stack and Queue

In this article, we will learn about the major differences between Stack and Queue data structures. What is a stack? Stack – A stack is an abstract data structure defined as the...

3 minutes read.

Bin Packing Problem (How to minimize the number of used Bins)

You have been given an array. The values of the array represent the size of n different items. You have been also given some bins. You have to store the...

3 minutes read.

Construction of B tree in Data Structure

A B-tree is a type of balanced tree data structure that is commonly used in file systems and databases to improve the efficiency of search, insert, and delete operations. The structure...

4 minutes read.

Heap Sort vs Merge Sort

In this article, we are going to discuss the Heap Sort, Merge sort and the difference between them. What is Heap Sort? Heap – A heap is an abstract data type categorised...

7 minutes read.

Symmetric binary tree

Implementation // writing a C++ program to check whether a given binary tree is symmetric or not. #include <bits/stdc++.h> using namespace std; // creating a binary tree node. struct __Nod { int ky; struct __Nod *Lft, *Rt; }; //...

4 minutes read.

Tree terminology in Data structures

Data structures The storage used to organize and store data is known as a data structure, and it is a method where data can be arranged on a computer to be...

6 minutes read.