Check if a linked list is Circular Linked List - GeeksforGeeks

07 Jul, 2021
Given a singly linked list, find if the linked list is circular or not. A linked list is called circular if it is not NULL-terminated and all nodes are connected in the form of a cycle. Below is an example of a circular linked list. 
An empty linked list is considered as circular.Note that this problem is different from cycle detection problem, here all nodes have to be part of cycle. 
The idea is to store head of the linked list and traverse it. If we reach NULL, linked list is not circular. If reach head again, linked list is circular.  
C++
Java
Python3
C#
Javascript
// C++ program to check if linked list is circular#include<bits/stdc++.h>using namespace std; /* Link list Node */struct Node{    int data;    struct Node* next;}; /* This function returns true if given linked   list is circular, else false. */bool isCircular(struct Node *head){    // An empty linked list is circular    if (head == NULL)       return true;     // Next of head    struct Node *node = head->next;     // This loop would stop in both cases (1) If    // Circular (2) Not circular    while (node != NULL && node != head)       node = node->next;     // If loop stopped because of circular    // condition    return (node == head);} // Utility function to create a new node.Node *newNode(int data){    struct Node *temp = new Node;    temp->data = data;    temp->next = NULL;    return temp;} /* Driver program to test above function*/int main(){    /* Start with the empty list */    struct Node* head = newNode(1);    head->next = newNode(2);    head->next->next = newNode(3);    head->next->next->next = newNode(4);     isCircular(head)? cout << "Yes\n" :                      cout << "No\n" ;     // Making linked list circular    head->next->next->next->next = head;     isCircular(head)? cout << "Yes\n" :                      cout << "No\n" ;     return 0;}
// Java program to check if// linked list is circularimport java.util.*; class GFG{     /* Link list Node */static class Node{    int data;    Node next;} /*This function returns true if given linkedlist is circular, else false. */static boolean isCircular( Node head){    // An empty linked list is circular    if (head == null)    return true;     // Next of head    Node node = head.next;     // This loop would stop in both cases (1) If    // Circular (2) Not circular    while (node != null && node != head)    node = node.next;     // If loop stopped because of circular    // condition    return (node == head);} // Utility function to create a new node.static Node newNode(int data){    Node temp = new Node();    temp.data = data;    temp.next = null;    return temp;} /* Driver code*/public static void main(String args[]){    /* Start with the empty list */    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\n" :                    "No\n" );     // Making linked list circular    head.next.next.next.next = head;     System.out.print(isCircular(head)? "Yes\n" :                    "No\n" ); }} // This code contributed by Arnab Kundu
# A simple Python program to check if a linked list is circular # Node classclass Node:     # Function to initialise the node object    def __init__(self, data):        self.data = data # Assign data        self.next = None # Initialize next as null  # Linked List class contains a Node objectclass LinkedList:     # Function to initialize head    def __init__(self):        self.head = None def Circular(head):    if head==None:        return True             # Next of head    node = head.next    i = 0         # This loop would stop in both cases (1) If    # Circular (2) Not circular    while((node is not None) and (node is not head)):        i = i + 1        node = node.next         return(node==head)  # Code execution starts hereif __name__=='__main__':    llist = LinkedList()    llist.head = Node(1)    second = Node(2)    third = Node(3)    fourth = Node(4)         llist.head.next = second;    second.next = third;    third.next = fourth         if (Circular(llist.head)):        print('Yes')    else:        print('No')         fourth.next = llist.head         if (Circular(llist.head)):        print('Yes')    else:        print('No')         # This code is contributed by Sanket Badhe
// C# program to check if// linked list is circularusing System;public class GFG{     /* Link list Node */public class Node{    public int data;    public Node next;} /*This function returns true if given linkedlist is circular, else false. */static bool isCircular( Node head){    // An empty linked list is circular    if (head == null)    return true;     // Next of head    Node node = head.next;     // This loop would stop in both cases (1) If    // Circular (2) Not circular    while (node != null && node != head)    node = node.next;     // If loop stopped because of circular    // condition    return (node == head);} // Utility function to create a new node.static Node newNode(int data){    Node temp = new Node();    temp.data = data;    temp.next = null;    return temp;} /* Driver code*/public static void Main(String []args){    /* Start with the empty list */    Node head = newNode(1);    head.next = newNode(2);    head.next.next = newNode(3);    head.next.next.next = newNode(4);     Console.Write(isCircular(head)? "Yes\n" :                    "No\n" );     // Making linked list circular    head.next.next.next.next = head;     Console.Write(isCircular(head)? "Yes\n" :                    "No\n" ); }}// This code has been contributed by 29AjayKumar
<script>// javascript program to check if// linked list is circular     /* Link list Node */class Node {    constructor(val) {        this.data = val;        this.next = null;    }}      /*     * This function returns true if given linked list is circular, else false.     */    function isCircular( head) {        // An empty linked list is circular        if (head == null)            return true;         // Next of head         node = head.next;         // This loop would stop in both cases (1) If        // Circular (2) Not circular        while (node != null && node != head)            node = node.next;         // If loop stopped because of circular        // condition        return (node == head);    }     // Utility function to create a new node.    function newNode(data) {         temp = new Node();        temp.data = data;        temp.next = null;        return temp;    }     /* Driver code */             /* Start with the empty list */         head = newNode(1);        head.next = newNode(2);        head.next.next = newNode(3);        head.next.next.next = newNode(4);         document.write(isCircular(head) ? "Yes<br/>" : "No<br/>");         // Making linked list circular        head.next.next.next.next = head;         document.write(isCircular(head) ? "Yes<br/>" : "No<br/>"); // This code contributed by gauravrajput1</script>
Output : 
No
Yes
YouTubeGeeksforGeeks507K subscribersCheck if a linked list is Circular Linked List | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:41•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=ce2rnhkNLzU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
?list=PLqM7alHXFySH41ZxzrPNj2pAYPOI8ITe7This article is contributed by Shivam Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
 
andrew1234
29AjayKumar
Sanket Badhe
Mk raghav
nidhi_biet
ayushbhardwaj5588
GauravRajput1
circular linked list
MAQ Software
Microsoft
SAP Labs
Linked List
Microsoft
MAQ Software
SAP Labs
Linked List
circular linked list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
LinkedList in Java
Linked List vs Array
Doubly Linked List | Set 1 (Introduction and Insertion)
Detect loop in a linked list
Merge two sorted linked lists
Find the middle of a given linked list
Implement a stack using singly linked list
Queue - Linked List Implementation
Implementing a Linked List in Java using Class
Circular Linked List | Set 1 (Introduction and Applications)