思路: 想像一下两个人在操场上跑步,起点相同,快的是不是最后一定会追上慢的。所以在有环的链表中fast指针总是比slow指针走快一步,则每一次slow到fast的距离都会+1,而fast到slow的距离会-1,则fast最后一定会和slow相遇。
知道上述原理之后代码实现就简单了
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode*fast=head;
ListNode*slow=head;
while(slow->next!=NULL&&fast->next!=NULL&&fast->next->next!=NULL)
{
fast=fast->next->next;
slow=slow->next;
if(fast==slow){return true;}
}
return false;
}
};
这位力扣上的大佬解释的更清楚
大佬的解题思路