解題思路:
(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==NULL||head->next==NULL) return false;
auto fast = head->next,slow = head;
while(fast!=slow) {
if(fast==NULL || fast->next==NULL) return false;
slow = slow->next;
fast = fast->next->next;
}
return true;
}
};