Given a single linked list, we have to detect loop. For this we will use two pointers called slow and fast. We will increment slow by one and fast by two. once both these pointers meet, this is the node from were loop is present
public void DetectLoop(Node<T> node) { Node<T> slow = node; Node<T> fast = node; while (slow != fast && fast.Next != null) { slow = slow.Next; fast = fast.Next.Next; if (slow == fast) { Console.WriteLine("Loop is detected"); return; } } Console.WriteLine("There is no loop"); }
Filed under:
LinkList
Leave a comment