Detect loop in a linked list | C ++ 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 ; Driver code ; Start with the empty list ; Create a loop for testing
#include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * next ; } ; void push ( Node * * head_ref , int new_data ) { Node * new_node = new Node ( ) ; new_node -> data = new_data ; new_node -> next = ( * head_ref ) ; ( * head_ref ) = new_node ; } int detectLoop ( Node * list ) { Node * slow_p = list , * fast_p = list ; while ( slow_p && fast_p && fast_p -> next ) { slow_p = slow_p -> next ; fast_p = fast_p -> next -> next ; if ( slow_p == fast_p ) { return 1 ; } } return 0 ; } int main ( ) { Node * head = NULL ; push ( & head , 20 ) ; push ( & head , 4 ) ; push ( & head , 15 ) ; push ( & head , 10 ) ; head -> next -> next -> next -> next = head ; if ( detectLoop ( head ) ) cout << " Loop ▁ found " ; else cout << " No ▁ Loop " ; return 0 ; }