【剑指offer】—— 链表中环的入口结点

题目描述

给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。

解答:

//链表结构
struct ListNode{
	int val;
	struct ListNode* next;
};
//找到相遇结点
//快指针一次走两步,慢指针一次走一步
//若两个指针相遇则存在环,若快指针走到NULL,则无环
ListNode* MeetingNode(ListNode* head)
{
	if(head==NULL)
		return NULL;

	ListNode* pSlow=head->next;
	if(pSlow==NULL)
		return NULL;

	ListNode* pFast=pSlow->next;

	while(pFast!=NULL&&pSlow!=NULL)
	{
		if(pFast=pSlow)
			return pFast;

		pSlow=pSlow->next;

		pFast=pFast->next;
		if(pFast!=NULL)
			pFast=pFast->next;
	}
	return NULL;
}
//找到入口
ListNode* EntryNode(ListNode* head)
{
	ListNode* mettingNode=MeetingNode(head);
	if(mettingNode==NULL)
		return NULL;
	int loopNode=1;

	ListNode* p1=mettingNode;
	//求出环中节点个数
	while(p1->next!=mettingNode)
	{
		p1=p1->next;
		++loopNode;
	}
	p1=head;
	int i=0;
	//先移动p1,移动次数为LoopNode
	for(i;i<loopNode;i++)
	{
		p1=p1->next;
	}
	ListNode* p2=head;
	//在同时移动p1,p2,两个指针相距loopNode的距离,相遇位置一定就是环的入口
	while(p1!=p2)
	{
		p1=p1->next;
		p2=p2->next;
	}
	return p1;
}



发布了160 篇原创文章 · 获赞 316 · 访问量 10万+

猜你喜欢

转载自blog.csdn.net/ShawnWang1994/article/details/99706681