数据结构 单链表——环的判断

判断链表是否有环? 若有,找出环入口结点?

相关头文件在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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值