×

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

Linear vs Non-Linear: Data Structure

What is Linear Data Structure? The data structure is said to be linear if the data elements are arranged linearly or we can say sequentially. In the linear data structure, the...

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

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.

Segregate Even and Odd nodes in a Linked List

Segregate even and odd nodes in a Linked List In this problem, we have given a linked list with integer numbers. We need to modify the given linked list in such...

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

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.

Heap Sort in Data Structure

Heap Sort A heap is a tree-based data structure that has specific properties. Heap is always a complete binary tree (CBT). That is, all the nodes of the tree are completely filled.If...

6 minutes read.

Minimum Spanning Tree

Before getting to know about the minimum spanning tree, we should first discuss about what is a spanning tree. A spanning tree is basically a sub or minimized graph that...

7 minutes read.

Difference between Structured and Object-Oriented Analysis

Analysis means observing and collecting relevant information about the structure of something or the basic details of a system's requirements. Structured and Object Oriented Analysis are both widely used in...

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

Insertion sort

Insertion sort is a simple sorting technique. It is best suited for small data sets, but it does not suitable for large data sets. In this technique, we pick an...

4 minutes read.

Types of Data Structures

Almost every programme or software system that has been built makes use of data structures. Furthermore, data structures are basics of computer science and software engineering. When it comes to...

7 minutes read.

Comb Sort

Brush sort is a fairly direct orchestrating computation at first arranged by Wlodzimierz Dobosiewicz and Artur Borowy in 1980, later rediscovered (and given the name "Combsort") by Stephen Lacey and...

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

Delete nodes from the linked list which have a greater value on the right side

Delete nodes from the linked list which have a greater value on the right side In this problem, we have given a singly linked list, and we need to remove all...

3 minutes read.

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.

Right side view of binary tree

The right view of the binary tree is generally known to be that side viewed from the right direction of the point of view. To be more precise, the right-side...

8 minutes read.

Binary Search Tree vs AVL Tree: Data Structure

Difference Between Binary Search Tree and AVL Tree Binary Search Tree: The binary search tree is a kind of binary tree data structure and it follows the conditions of binary...

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

Left View of Binary Tree

Implementation // creating a C++ program to print the Left view of the binary tree. #include <bits/stdc++.h> using namespace std; struct Nod { int record; struct Nod *Lft, *Rt; }; // creating a utility function that will eventually help...

4 minutes read.