每天一道LeetCode-----判断链表是否有环，如果有，找到环的入口位置

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
while(runner && runner->next)
{
walker = walker->next;
runner = runner->next->next;
if(walker == runner)
return true;
}
return false;
}
};

n=1 $n=1$时，即快指针在相遇之前多走了一圈，即 L+S=R $L+S=R$，也就是 L=RS $L=R-S$，观察图片， L $L$表示从链表头到环入口的距离，而RS$R-S$表示从 cross $cross$继续移动到环入口的距离，既然二者是相等的，那么如果采用两个指针，一个从表头出发，一个从 cross $cross$出发，那么它们将同时到达环入口。即二者相等时便是环入口节点

n>1 $n>1$时，上式为 L=nRS $L=nR-S$ L $L$仍然表示从链表头到达环入口的距离，而nRS$nR-S$可以看成从 cross $cross$出发移动 nR $nR$步后再倒退 S $S$步，从cross$cross$移动 nR $nR$步后回到 cross $cross$位置，倒退 S <script type="math/tex" id="MathJax-Element-36">S</script>步后是环入口，所以也是同时到达环入口。即二者相等时便是环入口节点

/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
while(runner && runner->next)
{
walker = walker->next;
runner = runner->next->next;
if(walker == runner)
break;
}
if(!runner || !runner->next)
return nullptr;
auto crossWalker = walker;
{
crossWalker = crossWalker->next;
}
}
};

求环的长度

int cycleLen(ListNode* head)
{
int len = 1;
auto walker = cycleIn;
while(walker->next != cycleIn)
{
++len;
walker = walker->next;
}
return len;
}

int cycleLen(ListNode* head)
{
while(runner && runner->next)
{
walker = walker->next;
runner = runner->next;
if(walker == runner)
break;
}
int len = 0;
while(runner && runner->next)
{
++len;
walker = walker->next;
runner = runner->next;
if(walker == runner)
break;
}
return len;
}
02-09 1218
06-02 5227

08-03 8855
03-29 3473
07-26 1万+
05-03 58
01-13 9100
07-10 3353
07-17 99