题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
先判断有没有环,用快慢指针判断,
如果有环,那么把快慢指针交点处拆开,那么寻找环的入口地址就变成了找两条链表的交点问题
找两条链表交点最大问题就是两个链表的长度可能不一样长
那么我们把两个链表分别互相+起来,从两条同样长的链表中找到第一个相等的节点
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead)
{
ListNode* pFast = pHead;
ListNode* pSlow = pHead;
ListNode* temp;
while(pFast->next)
{
pFast = pFast->next->next;
pSlow = pSlow->next;
if(pFast == pSlow)
{
temp = pFast;
break;
}
}
if(pFast->next != NULL)
{
pFast = temp->next;
pSlow = pHead;
while(pFast!= pSlow)
{
pFast = (pFast == temp ? pHead : pFast->next);
pSlow = (pSlow == temp ? temp->next : pSlow->next);
}
return pFast;
}
return NULL;
}
};