标签:环形链表,双指针,快慢指针
/**
* 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 == nullptr || head->next == nullptr) {
return false;
}
ListNode *s = head;
ListNode *f = head->next;
while (f->next != nullptr && f->next->next != nullptr) {
if (f == s) {
return true;
} else {
s = s->next;
f = f->next->next;
}
}
return false;
}
};