/**
* 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) {
if(head==NULL)
return false;
ListNode *slow=head; //设置一个快指针和一个慢指针,使他们都初始为head
ListNode *fast=head; //slow每次进一格,fast每次进两格
//如若有环则必定相遇
while(fast!=NULL&&fast->next!=NULL)
{
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
return true;
}
return false;
}
};具体图解*****

京公网安备 11010502036488号