Detect loop in a linked list | C # program to detect loop in a linked list ; head of list ; Linked list Node ; Inserts a new Node at front of the list . ; 1 & 2 : Allocate the Node & Put in the data ; 3. Make next of new Node as head ; 4. Move the head to point to new Node ; Driver code ; Start with the empty list ; Create loop for testing
using System ; public class LinkedList { Node head ; public class Node { public int data ; public Node next ; public Node ( int d ) { data = d ; next = null ; } } public void push ( int new_data ) { Node new_node = new Node ( new_data ) ; new_node . next = head ; head = new_node ; } Boolean detectLoop ( ) { Node slow_p = head , fast_p = head ; while ( slow_p != null && fast_p != null && fast_p . next != null ) { slow_p = slow_p . next ; fast_p = fast_p . next . next ; if ( slow_p == fast_p ) { return true ; } } return false ; } public static void Main ( String [ ] args ) { LinkedList llist = new LinkedList ( ) ; llist . push ( 20 ) ; llist . push ( 4 ) ; llist . push ( 15 ) ; llist . push ( 10 ) ; llist . head . next . next . next . next = llist . head ; Boolean found = llist . detectLoop ( ) ; if ( found ) { Console . WriteLine ( " Loop ▁ Found " ) ; } else { Console . WriteLine ( " No ▁ Loop " ) ; } } }