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.
// C program to check if the linked list is circular
// If linked list is empty it is circular
if(head == NULL)
ptr = head->next;
// Traversing linked list till last node
while(ptr != NULL && ptr != head)
ptr = ptr->next;
// Condition for circular linked list
return(ptr == head);
// Function to create new Node
temp = (structNode*)malloc(sizeof(structNode));
temp->data = data;
temp->next = NULL;
// Starting with empty list
structNode* head = newnode(1);
head->next = newnode(2);
head->next->next = newnode(3);
head->next->next->next = newnode(4);
// Checking for circular list
// If not circular making it circular
head->next->next->next->next = head;
Time Complexity: O(n)
As we have to move through the list at least one time whether it is circular or not.
Auxiliary Space: O(1)
As constant extra space is used.
This 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 email@example.com. 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