目录
b.slow一次走1步,fast走3步 4步 5步 n步还一定追得上吗 请证明
1.环形链表
思路:
快慢指针,慢指针走一步,快指针走两步
进环以后快指针开始追击慢指针
当快指针能追上慢指针就证明链表带环
bool hasCycle(struct ListNode *head) {
struct ListNode*fast=head,*slow=head;
while(fast&&fast->next)
{
slow=slow->next;
fast=fast->next->next;
if(fast==slow)
{
return true;
}
}
return false;
}
面试问题:
a.为什么一定会相遇,有没有可能会错过,永远追不上?请证明
假设slow进环时,fast跟slow距离时N,fast追击slow的过程中距离变化如下:
N
N-1
N-2
...
2
1
0
每追击一次,距离缩小1,距离为0就是追上了