Given the head of a singly linked list, the task is to find if given linked list is circular or not. A linked list is called circular if its last node points back to its first node.
Note: The linked list does not contain any internal loops.
Example:
Input: LinkedList: 2->4->6->7->5
Output: true Explanation: As shown in figure the first and last node is connected, i.e. 5 -> 2
Input: LinkedList: 2->4->6->7->5->1
Output: false Explanation: As shown in figure this is not a circular linked list.
[Expected Approach-1] By Traversing each node - O(n) time and O(1) space
The main idea is to traverse through the each node of linked list and check if the head->next pointer points back to the starting node (temp). If it does, that means the linked list is circular.
Code Implementation:
C++
// C++ program to check if linked list is circular#include<bits/stdc++.h>usingnamespacestd;structNode{intdata;Node*next;Node(intx){data=x;next=NULL;}};// This function returns true if given linked// list is circular, else false.boolisCircular(Node*head){// If the head is null, the linked list is empty,// so it is circularif(!head)returntrue;// Traverse the linked list until either the end// is reached or the next node is equal to the headNode*curr=head;while(curr&&curr->next!=head)curr=curr->next;// If the end is reached before finding// the head again, the linked list is not circularif(!curr)returnfalse;// If the head is found again before reaching// the end, the linked list is circularreturntrue;}intmain(){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 circularhead->next->next->next->next=head;isCircular(head)?cout<<"Yes\n":cout<<"No\n";return0;}
C
// C program to check if the linked list is circular#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};structNode*createNode(intdata);// Function to check if the linked list is circularintisCircular(structNode*head){// If head is null, list is empty, circularif(!head)return1;structNode*temp=head;// Traverse until the end is reached or // the next node equals the headwhile(head&&head->next!=temp)head=head->next;// If end reached before finding head again,// list is not circularif(!head||!(head->next))return0;// If head found again, list is circularreturn1;}structNode*createNode(intdata){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=data;newNode->next=NULL;returnnewNode;}intmain(){structNode*head=createNode(1);head->next=createNode(2);head->next->next=createNode(3);head->next->next->next=createNode(4);// Check if the linked list is circularisCircular(head)?printf("Yes\n"):printf("No\n");// Making the linked list circularhead->next->next->next->next=head;// Check again if the linked list is circularisCircular(head)?printf("Yes\n"):printf("No\n");return0;}
Java
// Java program to check if// linked list is circularclassNode{intdata;Nodenext;Node(intdata){this.data=data;this.next=null;}}classGfG{// Function to check if the linked list is circularstaticbooleanisCircular(Nodehead){// If head is null, list is empty, circularif(head==null)returntrue;Nodetemp=head;// Traverse until the end is reached or// the next node equals the headwhile(head!=null&&head.next!=temp)head=head.next;// If end reached before finding head again,// list is not circularif(head==null||head.next==null)returnfalse;// If head found again, list is circularreturntrue;}publicstaticvoidmain(String[]args){Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);// Check if the linked list is circularSystem.out.println(isCircular(head)?"Yes":"No");// Making the linked list circularhead.next.next.next.next=head;// Check again if the linked list is circularSystem.out.println(isCircular(head)?"Yes":"No");}}
Python
# Python program to check if linked list is circularclassNode:def__init__(self,data):self.data=dataself.next=None# Function to check if the linked list is circulardefis_circular(head):# If head is null, list is empty, circularifnothead:returnTruetemp=head# Traverse until the end is reached or# the next node equals the headwhileheadandhead.next!=temp:head=head.next# If end reached before finding head again,# list is not circularifnotheadornothead.next:returnFalse# If head found again, list is circularreturnTrueif__name__=="__main__":head=Node(1)head.next=Node(2)head.next.next=Node(3)head.next.next.next=Node(4)# Check if the linked list is circularprint("Yes"ifis_circular(head)else"No")# Making the linked list circularhead.next.next.next.next=head# Check again if the linked list is circularprint("Yes"ifis_circular(head)else"No")
C#
// C# program to check if// linked list is circularusingSystem;classNode{publicintdata;publicNodenext;publicNode(intdata){this.data=data;this.next=null;}}classGfG{// Function to check if the linked list is circularstaticboolIsCircular(Nodehead){// If head is null, list is empty, circularif(head==null)returntrue;Nodetemp=head;// Traverse until the end is reached or// the next node equals the headwhile(head!=null&&head.next!=temp)head=head.next;// If end reached before finding head again,// list is not circularif(head==null||head.next==null)returnfalse;// If head found again, list is circularreturntrue;}staticvoidMain(string[]args){Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);// Check if the linked list is circularConsole.WriteLine(IsCircular(head)?"Yes":"No");// Making the linked list circularhead.next.next.next.next=head;// Check again if the linked list is circularConsole.WriteLine(IsCircular(head)?"Yes":"No");}}
JavaScript
// JavaScript program to check if linked list is circular// Class representing a node in the listclassNode{constructor(data){this.data=data;this.next=null;}}// Function to check if the linked list is circularfunctionisCircular(head){// If head is null, list is empty, circularif(!head)returntrue;lettemp=head;// Traverse until the end is reached or// the next node equals the headwhile(head&&head.next!==temp)head=head.next;// If end reached before finding head again,// list is not circularif(!head||!head.next)returnfalse;// If head found again, list is circularreturntrue;}// Main partlethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);// Check if the linked list is circularconsole.log(isCircular(head)?"Yes":"No");// Making the linked list circularhead.next.next.next.next=head;// Check again if the linked list is circularconsole.log(isCircular(head)?"Yes":"No");
Output
No
Yes
Time Complexity: O(n), We traverse the linked list in the worst case once, therefore, the time complexity here is linear. Auxiliary Space: O(1), We are not using any extra space.
[Expected Approach-2] By Maintaining Slow & Fast Pointers - O(n) time and O(1) space
The idea is to use two pointers, slow and fast, to traverse the linked list. The slow pointer moves one step at a time, while the fast pointer moves two steps at a time. If the list is circular, the fast pointer will eventually meet the slow pointer; otherwise, the fast pointer will reach NULL indicating the list is not circular.
Code Implementation:
C++
// C++ program to check if linked list is circular#include<bits/stdc++.h>usingnamespacestd;structNode{intdata;structNode*next;Node(intx){data=x;next=NULL;}};// Function to check if the linked list is circularboolisCircular(Node*head){if(!head){returntrue;}Node*slow=head;Node*fast=head->next;while(fast&&fast->next){if(slow==fast){returntrue;}slow=slow->next;fast=fast->next->next;}returnfalse;}intmain(){structNode*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 circularhead->next->next->next->next=head;isCircular(head)?cout<<"Yes\n":cout<<"No\n";return0;}
C
// C program to check if linked list is circular#include<stdio.h>#include<stdlib.h>structNode{intdata;structNode*next;};structNode*createNode(intdata);// Function to check if the linked list is circularintisCircular(structNode*head){if(!head)return1;structNode*slow=head,*fast=head->next;// Traverse the linked list with two pointerswhile(fast&&fast->next){if(slow==fast)return1;slow=slow->next;fast=fast->next->next;}return0;}// Function to create a new nodestructNode*createNode(intdata){structNode*newNode=(structNode*)malloc(sizeof(structNode));newNode->data=data;newNode->next=NULL;returnnewNode;}intmain(){structNode*head=createNode(1);head->next=createNode(2);head->next->next=createNode(3);head->next->next->next=createNode(4);// Check if the linked list is circularisCircular(head)?printf("Yes\n"):printf("No\n");// Making the linked list circularhead->next->next->next->next=head;// Check again if the linked list is circularisCircular(head)?printf("Yes\n"):printf("No\n");return0;}
Java
// Java program to check if linked list is circularclassNode{intdata;Nodenext;Node(intdata){this.data=data;this.next=null;}}classGfG{// Function to check if the linked list is circularstaticbooleanisCircular(Nodehead){if(head==null)returntrue;Nodeslow=head,fast=head.next;// Traverse the linked list with two pointerswhile(fast!=null&&fast.next!=null){if(slow==fast)returntrue;slow=slow.next;fast=fast.next.next;}returnfalse;}publicstaticvoidmain(String[]args){Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);// Check if the linked list is circularSystem.out.println(isCircular(head)?"Yes":"No");// Making the linked list circularhead.next.next.next.next=head;// Check again if the linked list is circularSystem.out.println(isCircular(head)?"Yes":"No");}}
Python
# Python program to check if linked list is circularclassNode:def__init__(self,data):self.data=dataself.next=None# Function to check if the linked list is circulardefis_circular(head):ifnothead:returnTrueslow=headfast=head.nextwhilefastandfast.next:ifslow==fast:returnTrueslow=slow.nextfast=fast.next.nextreturnFalseif__name__=="__main__":head=Node(1)head.next=Node(2)head.next.next=Node(3)head.next.next.next=Node(4)# Check if the linked list is circularprint("Yes"ifis_circular(head)else"No")# Making the linked list circularhead.next.next.next.next=head# Check again if the linked list is circularprint("Yes"ifis_circular(head)else"No")
C#
// C# program to check if linked list is circularusingSystem;classNode{publicintdata;publicNodenext;publicNode(intdata){this.data=data;this.next=null;}}classGfG{// Function to check if the linked list is circularstaticboolIsCircular(Nodehead){if(head==null){returntrue;}Nodeslow=head;Nodefast=head.next;while(fast!=null&&fast.next!=null){if(slow==fast){returntrue;}slow=slow.next;fast=fast.next.next;}returnfalse;}staticvoidMain(string[]args){Nodehead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);// Check if the linked list is circularConsole.WriteLine(IsCircular(head)?"Yes":"No");// Making the linked list circularhead.next.next.next.next=head;// Check again if the linked list is circularConsole.WriteLine(IsCircular(head)?"Yes":"No");}}
JavaScript
// JavaScript program to check if linked list is circularclassNode{constructor(data){this.data=data;this.next=null;}}// Function to check if the linked list is circularfunctionisCircular(head){if(!head){returntrue;}letslow=head;letfast=head.next;while(fast&&fast.next){if(slow===fast){returntrue;}slow=slow.next;fast=fast.next.next;}returnfalse;}// Main partlethead=newNode(1);head.next=newNode(2);head.next.next=newNode(3);head.next.next.next=newNode(4);// Check if the linked list is circularconsole.log(isCircular(head)?"Yes":"No");// Making the linked list circularhead.next.next.next.next=head;// Check again if the linked list is circularconsole.log(isCircular(head)?"Yes":"No");
Output
false
Time Complexity: O(n), We traverse the linked list in the worst case once, therefore, the time complexity here is linear. Auxiliary Space: O(1), We use two Node pointers, slow and fast, so the extra space is constant.