在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 好听的元旦简短祝福语