在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 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短