题目
力扣链接:https://leetcode-cn.com/problems/linked-list-cycle/
思路:
数学题目–追加问题
理论证明:
证明一(这步非常关键!!!):
m%n=c; c%n=c;即m%n%n=c;
因为m%n得到的摸必然是小于n的,因此c%n=c;
证明二:
代码
bool hasCycle(struct ListNode *head) {
//本题通过快慢指针,通过理论证明,只要保证快慢指针速度差为1就行。
//当慢指针进环时,设快指针与它的距离x。因为速度差为1,快慢指针之间会逐渐靠近,直到相遇。
if(head==NULL)
{
return false;
}
struct ListNode *fast=head;
struct ListNode *slow=head;
while(1)
{
if((fast==NULL)||(fast->next==NULL)||(slow==NULL)||(slow->next==NULL))
{
return false;
}
else{
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
{
return true;
}
}
}
return false;
}
总结
数学不能忘!!!!。线代,高数,概率论,离散!!!!