Detect loop in a linked list | Java program to return first node of loop ; A utility function to print a linked list ; Function to detect first node of loop in a linked list that may contain loop ; Create a temporary node ; This condition is for the case when there is no loop ; Check if next is already pointing to temp ; Store the pointer to the next node in order to get to it in the next step ; Make next point to temp ; Get to the next node in the list ; Driver code ; Create a loop for testing ( 5 is pointing to 3 ) /
class GFG { static class Node { int key ; Node next ; } ; static Node newNode ( int key ) { Node temp = new Node ( ) ; temp . key = key ; temp . next = null ; return temp ; } static void printList ( Node head ) { while ( head != null ) { System . out . print ( head . key + " ▁ " ) ; head = head . next ; } System . out . println ( ) ; } static boolean detectLoop ( Node head ) { Node temp = new Node ( ) ; while ( head != null ) { if ( head . next == null ) { return false ; } if ( head . next == temp ) { return true ; } Node nex = head . next ; head . next = temp ; head = nex ; } return false ; } public static void main ( String args [ ] ) { Node head = newNode ( 1 ) ; head . next = newNode ( 2 ) ; head . next . next = newNode ( 3 ) ; head . next . next . next = newNode ( 4 ) ; head . next . next . next . next = newNode ( 5 ) ; head . next . next . next . next . next = head . next . next ; boolean found = detectLoop ( head ) ; if ( found ) System . out . println ( " Loop ▁ Found " ) ; else System . out . println ( " No ▁ Loop " ) ; } }