
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If a Linked List is Circular Linked List in C++
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
#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
Advertisements