您的位置:首页 > 其它

如何判断一个单链表中是否存在环

2013-09-01 09:30 513 查看
如何判断一个单链表是有环的?(注意不能用标志位,最多只能用两个额外指针)

struct node { char val; node* next;} 

bool check(const node* head) {} //return false : 无环;true: 有环一种O(n)的

办法就是(搞两个指针,一个每次递增一步,一个每次递增两步,如果有环的话两者必

然重合,反之亦然): 

bool check(const node* head) 


if(head==NULL || head->next == NULL) 
return false;
if(head->next == head)//存在自环
return true; 
node *low=head, *fast=head; 
while(fast!=NULL && fast->next!=NULL) 

low=low->next; 
fast=fast->next->next; 
if(low==fast) 
return true; 
}
return false;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: