板子题https://leetcode-cn.com/problems/linked-list-cycle/submissions/
又称快慢指针算法
本算法用来判断(链表)中是否存在环
显然若乌龟(慢)和兔子(快)在操场上跑步,无论两者谁先跑、从哪个地方起跑,一定存在某个时刻兔子与乌龟相遇
(逻辑题)
那么定义两个指针slow和fast,slow指针一次向后走一步,fast指针一次向后走两步,若两指针相遇则链表中必定有环
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
if(head == NULL || head->next==NULL)
return false;
struct ListNode *slow=head;
struct ListNode *fast=head->next;
while(slow != fast)
{
if(fast==NULL || fast->next==NULL)
return false;
slow=slow->next;
fast=fast->next->next;
}
return true;
}