判断链表是否有环? 若有,找出环入口结点?
相关头文件在blog里面
https://blog.csdn.net/weixin_43172803/article/details/103193039
#pragma warning(disable :4996)
#include <stdio.h>
#include "linetable_linktable.h"
List init(List head) {
head = (List)malloc(sizeof(link));
head->next = NULL;
}
List create_circle(List head) {
List arr, pr, t = NULL;
pr = head;
printf("The linktable has n numbers. Input n:\n");
int n = 0;
scanf("%d", &n);
if (n <= 0) {
printf("The linktable has nothing.\n");
return head;
}
printf("Please input the number the linktable has:\n");
for (int i = 1; i <= n; ++i) {
int m;
scanf("%d", &m);
arr = (List)malloc(sizeof(link));
pr->next = arr;
arr->data = m;
arr->next = NULL;
pr = pr->next;
if (i == n / 2)
t = pr;
}
pr->next = t;
return head;
}
int main() {
List p, fast, slow;
int flag = 0;
/* Create a circle linklist. */
List head = NULL;
head = init(head);
head = create_circle(head);
p = head;
fast = head->next;
slow = head->next;
if (!fast || !slow) {
printf("The linetable is not circle.\n");
}
else if(!fast->next || !fast->next->next){
printf("The linetable is not circle.\n");
}
else {
fast = fast->next;
fast = fast->next;
slow = slow->next;
while (fast && fast != slow) {
fast = fast->next;
fast = fast->next;
slow = slow->next;
}
if (!fast) {
printf("The linetable is not circle.\n");
}
else {
fast = head->next;
while (fast != slow) {
fast = fast->next;
slow = slow->next;
}
printf("The entering node is %d\n", fast->data);
}
}
return 0;
}