Data Structures Tutorial

Data Structures Tutorial Asymptotic Notation Structure and Union Array Data Structure Linked list Data Structure Type of Linked list Advantages and Disadvantages of linked list Queue Data Structure Implementation of Queue Stack Data Structure Implementation of Stack Sorting Insertion sort Quick sort Selection sort Heap sort Merge sort Bucket sort Count sort Radix sort Shell sort Tree Traversal of the binary tree Binary search tree Graph Spanning tree Linear Search Binary Search Hashing Collision Resolution Techniques

Misc Topic:

Priority Queue in Data Structure Deque in Data Structure Difference Between Linear And Non Linear Data Structures Queue Operations In Data Structure About Data Structures Data Structures Algorithms Types of Data Structures Big O Notations Introduction to Arrays Introduction to 1D-Arrays Operations on 1D-Arrays Introduction to 2D-Arrays Operations on 2D-Arrays Strings in Data Structures String Operations Application of 2D array Bubble Sort Insertion Sort Sorting Algorithms What is DFS Algorithm What Is Graph Data Structure What is the difference between Tree and Graph What is the difference between DFS and BFS Bucket Sort Dijkstra’s vs Bellman-Ford Algorithm Linear Queue Data Structure in C Stack Using Array Stack Using Linked List Recursion in Fibonacci Stack vs Array What is Skewed Binary Tree Primitive Data Structure in C Dynamic memory allocation of structure in C Application of Stack in Data Structures Binary Tree in Data Structures Heap Data Structure Recursion - Factorial and Fibonacci What is B tree what is B+ tree Huffman tree in Data Structures Insertion Sort vs Bubble Sort Adding one to the number represented an array of digits Bitwise Operators and their Important Tricks Blowfish algorithm Bubble Sort vs Selection Sort Hashing and its Applications Heap Sort vs Merge Sort Insertion Sort vs Selection Sort Merge Conflicts and ways to handle them Difference between Stack and Queue AVL tree in data structure c++ Bubble sort algorithm using Javascript Buffer overflow attack with examples Find out the area between two concentric circles Lowest common ancestor in a binary search tree Number of visible boxes putting one inside another Program to calculate the area of the circumcircle of an equilateral triangle Red-black Tree in Data Structures Strictly binary tree in Data Structures 2-3 Trees and Basic Operations on them Asynchronous advantage actor-critic (A3C) Algorithm Bubble Sort vs Heap Sort Digital Search Tree in Data Structures Minimum Spanning Tree Permutation Sort or Bogo Sort Quick Sort vs Merge Sort Boruvkas algorithm Bubble Sort vs Quick Sort Common Operations on various Data Structures Detect and Remove Loop in a Linked List How to Start Learning DSA Print kth least significant bit number Why is Binary Heap Preferred over BST for Priority Queue Bin Packing Problem Binary Tree Inorder Traversal Burning binary tree Equal Sum What is a Threaded Binary Tree? What is a full Binary Tree? Bubble Sort vs Merge Sort B+ Tree Program in Q language Deletion Operation from A B Tree Deletion Operation of the binary search tree in C++ language Does Overloading Work with Inheritance Balanced Binary Tree Binary tree deletion Binary tree insertion Cocktail Sort Comb Sort FIFO approach Operations of B Tree in C++ Language Recaman’s Sequence Tim Sort Understanding Data Processing Applications of trees in data structures Binary Tree Implementation Using Arrays Convert a Binary Tree into a Binary Search Tree Create a binary search tree Horizontal and Vertical Scaling Invert binary tree LCA of binary tree Linked List Representation of Binary Tree Optimal binary search tree in DSA Serialize and Deserialize a Binary Tree Tree terminology in Data structures Vertical Order Traversal of Binary Tree What is a Height-Balanced Tree in Data Structure Convert binary tree to a doubly linked list Fundamental of Algorithms Introduction and Implementation of Bloom Filter Optimal binary search tree using dynamic programming Right side view of binary tree Symmetric binary tree Trim a binary search tree What is a Sparse Matrix in Data Structure What is a Tree in Terms of a Graph What is the Use of Segment Trees in Data Structure What Should We Learn First Trees or Graphs in Data Structures All About Minimum Cost Spanning Trees in Data Structure Convert Binary Tree into a Threaded Binary Tree Difference between Structured and Object-Oriented Analysis FLEX (Fast Lexical Analyzer Generator) Object-Oriented Analysis and Design Sum of Nodes in a Binary Tree What are the types of Trees in Data Structure What is a 2-3 Tree in Data Structure What is a Spanning Tree in Data Structure What is an AVL Tree in Data Structure Given a Binary Tree, Check if it's balanced

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



ADVERTISEMENT
ADVERTISEMENT