题目描述
思路分析
链表+思维
经典快慢指针做法。快指针走两步,慢指针走一步,如果有环两者必然相遇,如果无环则快指针先到终点NULL;
代码实现
/**
* 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||!head->next) return false;
auto slow=head,fast=slow->next;
while(fast){
slow=slow->next;
fast=fast->next;
if(!fast) return false;
fast=fast->next;
if(fast==slow) return true;
}
return false;
}
};