Check if a Linked List is circular or not

05 min read

A Linked List is circular if it is not terminated by NULL and if all the nodes are connected in the form of a cycle as shown below.

Note: An empty linked list also acts as a circular linked list.

C++ program to check if the given linked list is circular or not is implemented below.

 

#include<bits/stdc++.h>
using namespace std;

struct Node
{
int data;
struct Node* next;
};


bool isCircular(struct Node *head) //function to check if LL is circular
{
if (head == NULL) //if the linked list is empty, it shows that it is circular
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\n" :
cout << "No\n" ;
head->next->next->next->next = head
isCircular(head)? cout << "Yes\n" :
cout << "No\n" ;
return 0;
}

 

Output :

No Yes
POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error