Check if a linked list is Circular Linked List in C++

C++Server Side ProgrammingProgramming

Here we will see, hoe to check a linked list is circular linked list or not. To check whether the linked list is circular or not, we will store the header node into some other variable, then traverse the list, if we get null at the next part of any node, then that is not circular, otherwise we will check the next node is same as the stored node or not, if so then that is circular.

Example

 Live Demo

#include <iostream>
using namespace std;
class Node{
   public:
   int data;
   Node *next;
};
Node* getNode(int data){
   Node *newNode = new Node;
   newNode->data = data;
   newNode->next = NULL;
   return newNode;
}
bool isCircularList(Node *start){
   if(start == NULL)
      return true;
   Node *node = start->next;
   while(node != NULL && node != start){
      node = node->next;
   }
   if(node == start)
      return true;
      return false;
}
int main() {
   Node *start = getNode(10);
   start->next = getNode(20);
   start->next->next = getNode(30);
   start->next->next->next = getNode(40);
   start->next->next->next->next = getNode(50);
   start->next->next->next->next->next = start;
   if (isCircularList(start))
      cout << "The list is circular list";
   else
      cout << "The list is not circular list";
}

Output

The list is circular list
raja
Published on 22-Oct-2019 14:56:41
Advertisements