Detect loop in a linked list | Java program to detect loop in a linked list ; Link list node ; Allocate node ; Put in the data ; Link the old list off the new node ; Move the head to point to the new node ; Returns true if there is a loop in linked list else returns false . ; If this node is already traverse it means there is a cycle ( Because you we encountering the node for the second time ) . ; If we are seeing the node for the first time , mark its flag as 1 ; Driver code ; Start with the empty list ; Create a loop for testing
import java . util . * ; class GFG { static class Node { int data ; Node next ; int flag ; } ; static Node push ( Node head_ref , int new_data ) { Node new_node = new Node ( ) ; new_node . data = new_data ; new_node . flag = 0 ; new_node . next = head_ref ; head_ref = new_node ; return head_ref ; } static boolean detectLoop ( Node h ) { while ( h != null ) { if ( h . flag == 1 ) return true ; h . flag = 1 ; h = h . next ; } return false ; } public static void main ( String [ ] args ) { Node head = null ; head = push ( head , 20 ) ; head = push ( head , 4 ) ; head = push ( head , 15 ) ; head = push ( head , 10 ) ; head . next . next . next . next = head ; if ( detectLoop ( head ) ) System . out . print ( " Loop ▁ found " ) ; else System . out . print ( " No ▁ Loop " ) ; } }