单链表找环入口节点

/*有环链表寻找入口节点
1、求环长度:快慢指针,一个指针走一步,一个走两步,当两个指针第一次相遇的时候,走的次数即是环长度
2、一个指针先走环的长度步数,另外一个指针从头开始, 然后两个指针同时走,第一次相遇即是环的入口节点*/
single_list_node* find_cricle_list_entrance(single_list_node* head)
{
	single_list_node* p1 = head, *p2 = head;
	int circle_len = 0, n = 0, len_entrance = 0;

	if(NULL == head)
	{
		return head;
	}

	while(  NULL != p1 && NULL != p2)
	{
		p1 = p1->next;
		p2 = p2->next;
		++circle_len;
		if(NULL != p2)
		{
			p2 = p2->next;
		}
		if(p1 == p2)
		{
			break;
		}
	}
	if(NULL == p2 || NULL == p1)
	{
		printf("the list has not cricle.\n\n");
		return NULL;
	}

	p1 = head;
	p2 = head;


	n = 0;
	while(n < circle_len)
	{
		p1 = p1->next;
		++n;
	}

	while(1)
	{
		if(p1 == p2)
		{
			break;
		}
		p1 = p1->next;
		p2 = p2->next;
		++len_entrance;
	}
	printf("circle_length = %d,  list len = %d\n", circle_len, (circle_len+ len_entrance));
	return p2;
}

测试用例:

	//环的尾部节点指向链表中间节点
	tmp = Find_middle_node(ls2);
	printf("ls2's middle node is %d\n\n", tmp->data);

    tail = find_single_linked_tail(ls2);
	tail->next = tmp;
	printf("tail node data = %d\n", tail->data);
//	SingleList_showdata_sleep(ls2);

	tmp2 = find_cricle_list_entrance(ls2);
	printf("The single linked list with Cricle , entrance node data = %d \n", tmp2->data);


	//无环链表
	tail->next = NULL;
	tmp2 = find_cricle_list_entrance(ls2);
	//一个节点成环
	tail->next = tail;
	tmp2 = find_cricle_list_entrance(ls2);
	printf("The single linked list with Cricle , entrance node data = %d \n", tmp2->data);
	//整个链表是一个大环
	tail->next = ls2;
	tmp2 = find_cricle_list_entrance(ls2);
	printf("The single linked list with Cricle , entrance node data = %d \n", tmp2->data);
    //一个节点的链表,无环
	ls3 = CreateSingleList(2);
	tmp2 = find_cricle_list_entrance(ls3);
    //一个节点的链表,有环
	ls3->next = ls3;
	tmp2 = find_cricle_list_entrance(ls3);
	printf("The single linked list with Cricle , entrance node data = %d \n", tmp2->data);

	ls3->next = NULL;
	ls3 = SingleList_insertHead(ls3,33);
	printf("ls3:\n");
	SingleList_showdata(ls3);
	//ls3 有两个节点,无环
	tmp2 = find_cricle_list_entrance(ls3);
	ls3->next->next = ls3->next;
	//两个节点,尾部节点自成环
	tmp2 = find_cricle_list_entrance(ls3);
	printf("The single linked list with Cricle , entrance node data = %d \n", tmp2->data);
	ls3->next->next = ls3;
	tmp2 = find_cricle_list_entrance(ls3);
	printf("The single linked list with Cricle , entrance node data = %d \n", tmp2->data);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值