Check if a linked list is Circular Linked List | C ++ program to check if linked list is circular ; Link list Node ; This function returns true if given linked list is circular , else false . ; An empty linked list is circular ; Next of head ; This loop would stop in both cases ( 1 ) If Circular ( 2 ) Not circular ; If loop stopped because of circular condition ; Utility function to create a new node . ; Driver program to test above function ; Start with the empty list ; Making linked list circular
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; struct Node * next ; } ; bool isCircular ( struct Node * head ) { if ( head == NULL ) return true ; struct Node * node = head -> next ; while ( node != NULL && node != head ) node = node -> next ; return ( node == head ) ; } Node * newNode ( int data ) { struct Node * temp = new Node ; temp -> data = data ; temp -> next = NULL ; return temp ; } int main ( ) { struct Node * head = newNode ( 1 ) ; head -> next = newNode ( 2 ) ; head -> next -> next = newNode ( 3 ) ; head -> next -> next -> next = newNode ( 4 ) ; isCircular ( head ) ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; head -> next -> next -> next -> next = head ; isCircular ( head ) ? cout << " Yes STRNEWLINE " : cout << " No STRNEWLINE " ; return 0 ; }