×

Detect and Remove Loop in a Linked List

Create a function called detectAndRemovetheLoop() that verifies whether a given Linked List has a loop, eliminates the loop if it does, and returns true if it does. It returns false if there is no loop in the list. The list below must be changed to 1 -> 2 -> 3 -> 4 -> 5 -> NULL via the detectAndRemovetheLoop() function.

We must first find the loop in order to attempt to delete it. To end the loop, all that is needed is a pointer to the last node. As in the node with the value 5 above. As soon as we are aware of the pointer to the last node, we can declare the following node in this loop to be NULL.

To obtain the pointer to the last node, we can simply utilise the hashing or visited node approaches. The basic principle is that the final node is the first node whose next has already been visited or hashed.

The Floyd Cycle Detection technique can be used to find and get rid of the loop as well. Floyd's algorithm's loop node is where the slow and fast pointers combine. This loop node can be used to get rid of the cycle. When Floyd's technique is used to detect loops, there are two possible approaches to break the loop.

How may a loop be found in a linked list?

The fast and slow pointer approach, in which the fast pointer advances by two nodes and the slow pointer moves by one node at a time, can effectively find loops.

Technique 1 (Check one by one): We are aware that Floyd's Cycle detection procedure ends when the fast and slow pointers collide at the same location. We also understand that this point is a loop node. In a pointer variable, such as ptr2, save the address of this. Then, beginning at the top of the Linked List, determine which nodes may be reached from ptr2 by checking them one at a time. It is possible to obtain the pointer to the preceding node of any reachable node in the Linked List, indicating that this node represents the beginning of the loop.

  • Get the pointer to a loop node by utilising Floyd's Cycle detection technique to find a loop.
  • Count how many nodes are in the loop. Let k be the count.
  • One pointer should be fixed to the head, and the other to a kth node from the head.
  • The pointers will collide at the loop's starting node if we move them both at the same speed.
  • Obtain a pointer to the loop's final node, and make the next one NULL.

C++ Program:

#include <bits/stdc++.h>
using namespace std;
struct Node 
{
	int data1;
	struct Node* next1;
};
void removetheLoop ( struct Node*, struct Node* );
int detectAndRemovetheLoop ( struct Node* list )
{
	struct Node *slow_po = list, *fast_po = list;
	while ( slow_po && fast_po && fast_po -> next1 ) 
	{
		slow_po = slow_po -> next1;
		fast_po = fast_po -> next1 -> next1;
		if ( slow_po == fast_po ) 
		{
			removetheLoop ( slow_po, list );
			return 1;
		}
	}
	return 0;
}
void removetheLoop ( struct Node* loop_node, struct Node* head )
{
	struct Node* ptr1 = loop_node;
	struct Node* ptr2 = loop_node;


	unsigned int k = 1, i;
	while ( ptr1->next1 != ptr2 ) 
	{
		ptr1 = ptr1->next1;
		k++;
	}
	ptr1 = head;
	ptr2 = head;
	for ( i = 0; i < k; i++ )
		ptr2 = ptr2->next1;
	while ( ptr2 != ptr1 ) 
	{
		ptr1 = ptr1->next1;
		ptr2 = ptr2->next1;
	}


	while ( ptr2->next1 != ptr1 )
		ptr2 = ptr2->next1;
	ptr2->next1 = NULL;
}
void printList ( struct Node* node )
{
	while ( node != NULL ) 
	{
		cout << node -> data1 << " ";
		node = node -> next1;
	}
}
struct Node* newNode ( int key )
{
	struct Node* temp = new Node();
	temp -> data1 = key;
	temp -> next1 = NULL;
	return temp;
}
int main()
{
	struct Node* head = newNode (60);
	head -> next1 = newNode (30);
	head -> next1 -> next1 = newNode (25);
	head -> next1 -> next1 -> next1 = newNode (14);
	head -> next1 -> next1 -> next1 -> next1 = newNode (20);
	head -> next1 -> next1 -> next1 -> next1 -> next1 = head -> next1 -> next1;
	detectAndRemovetheLoop (head);
	cout << "After the loop has been removed, the Linked List : \n";
	printList ( head );
	return 0;
}

Output:

After the loop has been removed, the Linked List :
60 30 25 14 20

Technique 2 (Loop without Counting Nodes): There is no requirement to count the nodes in a loop. After identifying the loop, if we move the fast and slow pointers at the same speed until the fast pointers don't meet, they will collide at the beginning of the loop.

How does that function?

Let the Floyd's Cycle finding algorithm lead to a point where slow and fast will collide. The scenario when the cycle is discovered is depicted in the diagram below.

C++ Program:

#include <stdio.h>
#include <stdlib.h>


typedef struct Node 
{
	int keys;
	struct Node* next1;
}
 Node;


Node* newNode ( int keys )
{
	Node* temp = ( Node* )malloc( sizeof (Node) );
	temp -> keys = keys;
	temp -> next1 = NULL;
	return temp;
}
void printtheList ( Node* head )
{
	while ( head != NULL ) 
	{
		printf ( "%d ", head->keys) ;
		head = head -> next1;
	}
	printf ("\n");
}
void detectAndRemovetheLoop ( Node* head )
{
	if ( head == NULL || head -> next1 == NULL )
		return;


	Node *slow = head, *fast = head;
	slow = slow -> next1;
	fast = fast -> next1 -> next1;


	while ( fast && fast -> next1)  
	{
		if ( slow == fast )
			break;
		slow = slow -> next1;
		fast = fast -> next1 -> next1;
	}
	if  (slow == fast )
	 {
		slow = head;


		if ( slow == fast )
			while ( fast -> next1 != slow )
				fast = fast -> next1;
		else
	   {
			while ( slow -> next1 != fast -> next1 )  
			{
				
				slow = slow -> next1;
				fast = fast -> next1;
			}
		}
		fast -> next1 = NULL; 
	}
}
int main ()
{
	Node* head = newNode (60);
	head -> next1 = head;
	head -> next1 = newNode (30);
	head -> next1 -> next1 = newNode (25);
	head -> next1 -> next1->next1= newNode (14);
	head -> next1 -> next1->next1->next1 = newNode (20);
	head -> next1 -> next1 -> next1 -> next1 -> next1 = head;
	detectAndRemovetheLoop (head);
	printf ("After the loop has been removed, the Linked List : \n");
	printtheList (head);
	return 0;
}

Output:

After the loop has been removed, the Linked List :
60 30 25 14 20

Technique 3 (Hashing: Hash the addresses of the nodes in the linked list): In an unordered map, we may simply check to see if an element already exists by hashing the addresses of the linked list nodes. If it exists, then we have reached a node that already exists after a cycle and must set the following node's reference to NULL.

C++ Program:

#include <bits/stdc++.h>
using namespace std;


struct Node 
{
	int keys;
	struct Node* next1;
};
Node* newNode ( int keys )
{
	Node* temp = new Node;
	temp -> keys = keys;
	temp -> next1 = NULL;
	return temp;
}
void printtheList ( Node* head )
{
	while ( head != NULL ) 
	{
		cout << head -> keys << " ";
		head = head -> next1;
	}
	cout << endl;
}
void hashAndRemoveit ( Node* head )
{
	unordered_map<Node*, int> node_map;


	Node* last = NULL;
	while ( head != NULL ) 
	{
		if ( node_map.find(head) == node_map.end() ) 
		{
			node_map [head]++;
			last = head;
			head = head -> next1;
		}
		else {
			last -> next1 = NULL;
			break;
		}
	}
}
int main ()
{
	Node* head = newNode (60);
	head -> next1 = head;
	head -> next1 = newNode (30);
	head -> next1 -> next1 = newNode (25);
	head -> next1 -> next1 -> next1 = newNode (14);
	head -> next1 -> next1 -> next1 -> next1 = newNode (20);




	head -> next1 -> next1 -> next1 -> next1 -> next1 = head -> next1 -> next1;
	hashAndRemoveit (head);
	printf ("After the loop has been removed, the Linked List : \n");
	printtheList (head);
	return 0;
}

Output:

After the loop has been removed, the Linked List :
60 30 25 14 20

Related Topics

B+ Tree in Data Structure

A B-Tree extension called B+ Tree, which enables effective search, insertion, and deletion operations. Both Records and keys can be stored in internal and leaf nodes in a B tree. Contrarily,...

4 minutes read.

Red Black Tree

Red Black Tree A red-black tree is referred as self-balancing binary search tree. The tree was invented by Rudolf Bayer in 1972. In red-black, each node stores an extra bit that...

8 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.

Number of visible boxes putting one inside another

You have given one array, which consists of values which represent the sizes of different boxes. We can put one box inside another if the size of the outside box...

3 minutes read.

Tim Sort

Tim Sort is a mixture stable arranging calculation that exploits normal examples in information, and uses a mix of an improved Merge sort and Binary Insertion sort alongside an interior...

6 minutes read.

Convert a Binary Tree into a Binary Search Tree

Implementation #include <stdio.h>   #include <stdlib.h>       //creating a node of the binary tree.  struct __nod{       int record;       struct __nod *Lft;       struct __nod *Rt;   };       // presenting the root of the binary tree.   struct...

5 minutes read.

Red-black Tree in Data Structures?

A type of binary tree which is known as the Red-Black tree, is a specialized and unique tree. What is the urgency or, to be more precise, the necessity of...

10 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.

Insertion in B+ Tree

We will learn how to insert a node in the B+ tree and what are the different properties we are going to follow. Except for the root node, every node should...

5 minutes read.

Binary search tree traversal in-order pre-order post-order examples

A binary search tree is a type of non-linear tree in which the tree contains at least two nods. It is called binary because of its nature that states bi...

8 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.

Boruvkas algorithm

This algorithm is used for finding minimum spanning tree from a weighted graph. Like prim’s and kruskal’s algorithm it is also a greedy algorithm. Note:What is the minimum spanning tree?We know...

4 minutes read.

Linear vs Circular Queue: Data Structure

Difference Between Linear and Circular Queue What is Linear Queue? A linear queue is linear data structure which works on first in first out principle. We can say a linear queue is...

3 minutes read.

Reverse a Linked List in groups of given size

Reverse a Linked List in groups of given size This article will explain how to reverse a linked list in groups of given size. Here we have given a linked list...

2 minutes read.

Radix Sort

Radix Sort: The radix sort is a non-comparative integer sorting algorithm that sorts the elements by grouping the individual digits of the same location. It shares the same significant position...

4 minutes read.

String Operations in Data Structures

Operations on Strings Reversing the order of words in a sentence Reversing a string is a technique that reverses or alters the order of a given string so that the last character...

9 minutes read.

Find Bridges in a Graph

You have been given a graph. You have to find out the bridges in that graph. Graph may be connected or disconnected. You have to print vertices of particular edge...

4 minutes read.

Blowfish algorithm

The Blowfish algorithm is the very first encryption algorithm which is symmetric. It was firstly used as an alternate algorithm for the DES algorithm. It was designed by Bruce Steiner...

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.

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.