1.设立2个指针i,j指向头结点
2.i走1步,j走2步.如果有环,j一定能追上i;
3.如果j不为空,且i和j相等此链表即为有环。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student //定义链表结构
{
int num;
struct student *pnext;
}stu,*pstu;
void link_tail_insert(pstu *phead,pstu *ptail,int i);
void link_show(pstu );
void link_judge_loop(pstu phead);
void main(){
pstu phead,ptail;
int i;
phead = NULL;
ptail = NULL;
while(scanf("%d",&i) != EOF){
link_tail_insert(&phead,&ptail,i);
}
link_show(phead);
ptail->pnext = phead; //单链表建立环
link_judge_loop(phead);
system("pause");
}
void link_tail_insert(pstu *phead,pstu *ptail,int i){ //尾插法建立链表
pstu pnew;
pnew = (pstu)malloc(sizeof(stu));
memset(pnew,0,sizeof(stu));
pnew->num = i;
if(*ptail == NULL){
*phead = pnew;
*ptail = pnew;
}
else{
(*ptail)->pnext = pnew;
*ptail = pnew;
}
}
void link_show(pstu phead){ //输出链表
pstu pshow;
pshow = phead;
if(phead == NULL)
{
printf("no exsit\n");
return;
}
while(pshow != NULL){
printf("%d ",pshow->num);
pshow = pshow->pnext;
}
putchar('\n');
}
void link_judge_loop(pstu phead){ //判断是否有环
pstu i,j;
i = j = phead;
while(j != NULL){
i = i->pnext;
j = j->pnext;
if(j == NULL) //j要分步走,判断是否为空,是空则结束循环
break;
j = j->pnext;
if(i == j) //i和j相等,有环
break;
}
if(j != NULL && i == j)
printf("link has loop\n");
else
printf("link has no loop\n");
}