检测单链表是否含有环

给定一个单链表,检测该链表是否含有环形结构。这个题目主要是根据环的特性,使用两个指针,不同的步长,向一个方向前进,如果有环,他们两个指针必定相遇。

#include <stdio.h>
#include
<malloc.h>

typedef
struct LNode{
int data;
struct LNode *next;
}LNode;

int isLoop(LNode *head){
LNode
*p=head,*q=head;
while( q && q->next ){
p
=p->next;
q
=q->next->next;
if(p==q) break;
}

return !(q==NULL||q->next==NULL);
}

int main(){
LNode
*head = (LNode *)malloc(sizeof(LNode));
LNode
*curr=head;
LNode
*start=NULL;
head
->next=NULL;
int i;
for( i=0;i<10;i++ ){
curr
->next = (LNode *)malloc(sizeof(LNode));
curr
=curr->next;
curr
->next=NULL;
if(i==5) start = curr;
}
curr
->next=start;
printf(
"%d",isLoop(head));
}
原文地址:https://www.cnblogs.com/codebean/p/2059892.html