#include<stdio.h>
#include<stdlib.h>
struct linknode
{
int data;
linknode *next;
};
int hasCycle(struct linknode *head)
{
struct linknode *fast, *slow;
fast = head;
slow = head;
while(fast && fast->next)
{
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
return true;
}
return false;
}
int main()
{
linknode *head = new linknode;
linknode *mhead = head;
for(int i = 0;i<10;i++)//构造链表
{
linknode *node = new linknode;
mhead->next = node;
mhead = node;
}
mhead->next = head;//尾节点指向头结点
printf("第一种方法\n");
linknode *cur=head->next;
int f=0;
while(cur)
{
if(cur==head)
{
printf("有环\n");
f=1;
break;
}
else{
cur=cur->next;
}
}
if(f==0){
printf("不存在环\n");
}
printf("第二种方法\n");
if(hasCycle(head)){
printf("存在环");
}else{
printf("不存在环\n");
}
return 0;
}
两种判断环状链表方法
最新推荐文章于 2024-05-24 12:22:29 发布