题解 | #链表中环的入口结点#

链表中环的入口结点

http://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4


typedef struct ListNode Node;

Node* MeetingNode(Node* head)
{
	int i;
	Node *node_f, *node_s;

	if (!head||!(head->next))
		return NULL;

	node_s = head->next;
	node_f = head->next;

	while (node_f && node_s)
	{
        node_s = node_s->next;

		node_f = node_f->next;
		if (node_f)
			node_f = node_f->next;
		if (node_f == node_s)
			return node_f;

		
	}

	return NULL;

}

struct ListNode* EntryNodeOfLoop(struct ListNode* pHead ) {
    int count = 1;
	int i = 0;
	Node* Meetingnode = MeetingNode(pHead);
	Node* node_1 = Meetingnode;
	Node* node_2 = pHead;
	if (Meetingnode == NULL)
		return NULL;
	while (node_1->next != Meetingnode)
	{
		node_1 = node_1->next;
		count++;
	}
	node_1 = pHead;
	for (i = 0; i < count; i++)
		node_1 = node_1->next;
	
	while (node_1 != node_2)
	{
		node_1 = node_1->next;
		node_2 = node_2->next;
	}
	return node_1;

}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务