#include <stdio.h> #include <stdlib.h> #define N 45 typedef struct Node { int key; struct Node * next; }Node; // 检测链表是否存在环 // 快慢指针方法实现 int loopCheck(Node * head) { Node *slow = head, *fast = head; while(fast != NULL && fast->next != NULL) { slow = slow->next; fast = fast->next->next; if(slow == fast) return 1; } return 0; } int main() { //创建有环链表 Node *head = malloc(sizeof(Node)); head->next = NULL; Node *current = head; Node *start; for ( int i = 0; i < 5000 ; i++ ) { current->next = malloc(sizeof(Node)); current = current->next; current->next = NULL; //保存指针以备建立环 if(i == N) { start = current; } } //current->next = start; //检测环是否存在 if(loopCheck(head)) printf("there is a loop in the link list./n"); else printf("there is no loop"); return 0; }