在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 << "列表不是循环列表";
}输出结果列表为循环列表
热门推荐
10 最真的新春祝福语简短
11 简短霸气的考试祝福语
12 画室蛋糕祝福语简短英文
13 公司年会亲属祝福语简短
14 虎年台词祝福语大全简短
15 新郎表白成语祝福语简短
16 参加儿子大学祝福语简短
17 孩子16岁祝福语简短
18 婚礼明星的祝福语简短