有很多种方式解决问题,我这里只说一种方法
使用p、q两个指针,p每次向前走一步,q每次向前走两步,若在某时候p == q,则存在环,如图:
代码实现:
#include <stdio.h>
#include <stdlib.h>
#define LEN 8
typedef struct node{
char val;
struct node *next;
}*node_t;
int has_loop2(node_t head);
int main()
{
node_t* arr = (node_t*)malloc(sizeof(struct node)*LEN);
arr[0] = (node_t)malloc(sizeof(struct node));
int i;
for(i = 1;i<LEN;i++)
{
arr[i]=(node_t)malloc(sizeof(struct node));
arr[i-1]->next = arr[i];
}
arr[LEN - 1]->next = NULL;
if(has_loop2(arr[0]))
printf("是环\n");
else
printf("不是环\n");
return 0;
}
int has_loop2(node_t head){
node_t p = head;
node_t q = head;
while(p!=NULL && q !=NULL)
{
p = p->next;//p走一步
if(q->next != NULL)
q = q->next->next;//q走两步
if(p == q)//如果相等则退出,否则继续走,直到重合
return 1;
p = p->next;
q = q->next;
if(q !=NULL)
q = q->next;
if(p!=NULL && p == q)
{
return 1;
}
}
return 0;
}