Every day a leetcode
题目来源:面试题 02.08. 环路检测
解法1:快慢指针
设置快慢两个指针分别为 fast 和 slow,初始化都指向 head。
slow 每次走一步,fast 每次走两步。
由于 fast 走得更快,如果有环,fast 一定先进入环,slow 后进入环。当两个指针都进入环后,两个指针一定能在环上相遇,这样就能判断是否有环。
如下图所示,当 slow 刚进入环时,fast 早已进入环。因为 fast 每次比 slow 多走一步,且 fast 和 slow 的距离小于环的长度,所以 fast 和 slow 相遇时,slow 所走的距离不超过环的长度。
如下图所示,设头结点到环的入口点的距离为 a,环的入口点沿环的方向到相遇点的距离为 x,环长为 r,相遇时 fast 绕了 n 圈。
则有:2 * (a + x) = a + n * r + x,即:a = n * r - x。
显然从头结点到环的入口点的距离等于 n 倍的环长减去环的入口点到相遇点的距离。
因此可以设置两个指针,一个指向 head,一个指向相遇点,两个指针同步移动(一次走一步),相遇点即为环的入口点。
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *detectCycle(struct ListNode *head) {
if(head == NULL || head->next == NULL) return NULL;
struct ListNode* slow=head;
struct ListNode* fast=head;
while(fast && fast->next)
{
slow=slow->next;
fast=fast->next->next;
if(slow == fast) break;
}
//没有环,返回NULL
if(fast!=slow) return NULL;
struct ListNode* p1=head;
struct ListNode* p2=slow;
while(p1!=p2)
{
p1=p1->next;
p2=p2->next;
}
return p1;
}
结果:
解法2:hash
详情见官方题解:环路检测:方法一:哈希表