在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 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短