Check if a linked list is Circular Linked List | Java 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 code ; Start with the empty list ; Making linked list circular
import java . util . * ; class GFG { static class Node { int data ; Node next ; } static boolean isCircular ( Node head ) { if ( head == null ) return true ; Node node = head . next ; while ( node != null && node != head ) node = node . next ; return ( node == head ) ; } static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . next = null ; return temp ; } 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 ) ; System . out . print ( isCircular ( head ) ? "Yes " ▁ : ▁ " No " ); head . next . next . next . next = head ; System . out . print ( isCircular ( head ) ? "Yes " ▁ : ▁ " No " ); } }