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


在本文中,我们将学习如何检查链表是否为循环链表。若要检查链表是否循环,我们将存储头节点到某个其他变量中,然后遍历列表,如果在任意节点的 next 部分获得 null,那么它就不循环,否则,我们将检查 next 节点是否与存储节点相同,如果是,那么它就是循环的。

示例

 实时演示

#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";
}

输出

The list is circular list

更新时间: 22-Oct-2019

2K+ 查看

开启您的 职业生涯

完成课程后获得认证

入门
广告
© . All rights reserved.