解题思路:
(1)设置快慢指针,只需要快指针是否到达末尾
/**
* 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) return false;
ListNode *slow=head,*fast=head;
while(fast && fast->next) {
fast=fast->next->next;
slow=slow->next;
if(slow==fast) return true;
}
return false;
}
};