在C++中检查链表是否是循环链表

在这里我们会看到,hoe检查链表是不是循环链表。为了检查链表是否是循环的,我们将头节点存储到另一个变量中,然后遍历链表,如果在任何节点的下一部分为空,则该链表不是循环的,否则我们将检查下一个节点是否与存储的节点相同,如果是,则该链表是循环的。

示例

#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 << "列表为循环列表";
   else
      cout << "列表不是循环列表";
}
输出结果
列表为循环列表