#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <Windows.h>
typedef int DataType;
typedef struct node
{
DataType data;
struct node* next;
}SingleList;
//初始化
SingleList* InitSingleList(SingleList* head)
{
head = NULL;
return head;
}
//创建无头单链表
SingleList* CreataSingleListByTail(SingleList* head)
{
SingleList* pmove = head;
SingleList* createNode = NULL;
DataType data;
int len;
printf("请输入要创建的无头单链表的长度:");
scanf_s("%d", &len);
printf("请输入数据:");
for (int i = 0; i < len; i++)
{
scanf_s("%d", &data);
createNode = (SingleList*)malloc(sizeof(SingleList));
if (createNode == NULL)
{
printf("申请内存空间失败!\n");
return NULL;
}
else
{
createNode->data = data;
createNode->next = NULL;
}
if (head == NULL)//处理第一个结点
{
head = createNode;
pmove = head;
}
else//从第二个结点开始按链表的尾插正常插入
{
pmove->next = createNode;
pmove = createNode;
}
}
return head;
}
//创建环形链表
SingleList* CycleSingleList(SingleList* head)
{
int pos, len = 1;
SingleList* pmove = head;
SingleList* qmove = head;
while (pmove->next != NULL)//找到链表的最后一位
{
pmove = pmove->next;
len++;
}
printf("请输入要成环的位置:");
scanf_s("%d", &pos);
if (pos<0 || pos>len)
{
printf("输入的成环位置不合法!\n");
return head;
}
for (int i = 0; i < pos-1; i++)
{
qmove = qmove->next;
}
pmove->next = qmove;//让链表的尾结点链接到成环位置
return head;
}
//判断链表是否有环
SingleList* IsCycleSingleList(SingleList* head)
{
if (head == NULL || head->next == NULL)
return NULL;
SingleList* fast, * slow;
fast = slow = head;
while (fast != NULL && fast->next != NULL)
{
slow = slow->next;
fast = fast->next->next;
if (fast == slow)//fast和slow相等时说明链表有环
{
fast = head;
while (fast != slow)//具体找入环的结点
{
slow = slow->next;
fast = fast->next;
}
return fast;
}
}
return NULL;
}
//打印
void PrintfSingleList(SingleList* head)
{
SingleList* pmove = head;
while (pmove != NULL)
{
printf("%3d", pmove->data);
pmove = pmove->next;
}
printf("\n");
}
int main(void)
{
SingleList* list = NULL, * mylist, * cyclist, * pos, * pmove;
int len=0;
list = InitSingleList(list);
mylist = CreataSingleListByTail(list);
cyclist = CycleSingleList(mylist);
pos = IsCycleSingleList(cyclist);
pmove = cyclist;
while (pos != pmove)//找成环的位置,下标从0开始
{
pmove = pmove->next;
len++;
}
if (pos != NULL)
{
printf("tail connects to node index:%d\n",len);
}
else
{
printf("no cycle\n");
}
system("pause");
return EXIT_SUCCESS;
}
05-18
229
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-07
356
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)