// TestLinkListCircle.cpp : Defines the entry point for the console application. //测试单链表是否有环,并找到入口: #include "stdafx.h" #include <malloc.h> #include <assert.h> typedef struct node Node; //单链表结构 struct node{ int value; Node *next; }; //创建一个单链表。 //创建头结点head,创建一个临时节点p,最后去掉头结点(head=head->next),将尾节点指向环的开始位置 Node* createLinkList(int start,int end,int cross){ assert(start>=0 && end>=0 && cross<=end && cross>=start); Node *head=(Node*)malloc(sizeof(Node));//头结点 if(head==NULL){ return NULL; } Node *p=head;//移动。加节点 Node *cross_point=NULL; int i=0; for(i=start;i<=end;i++){ Node *node=(Node*)malloc(sizeof(Node)); node->value=i;//设置节点的值 if (i==cross) { cross_point=node;//记录环的起始点 } p->next=node;//挂接 p=node;//移动 } head=head->next;//干掉头结点 p->next=cross_point;//下个节点为空 return head; } //寻找环的起始位置 Node* TestAndFindCircle(Node* head){ assert(head!=NULL); Node* fast=head; Node* slow=head; while(fast!=NULL && fast->next!=NULL){ fast=fast->next->next;//走两步 slow=slow->next;//走一步 if(slow==fast){//有环 fast=head; while(fast!=slow){ fast=fast->next; slow=slow->next; return fast; } } } return NULL; } int main(int argc, char* argv[]) { Node *linkList=createLinkList(1,5,2); Node *cross=TestAndFindCircle(linkList); if(cross!=NULL){ printf("环的起始值:%d/n",cross->value); }else{ printf("没有环"); } return 0; }