/**
* 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 *node1 = head;
ListNode *node2 = head->next;
while(node1 != node2){
if(node2 ==nullptr || node2->next == nullptr){
return false;
}
node1 = node1->next;
node2 = node2->next->next;
}
return true;
}
};
// class Solution {
// public:
// bool hasCycle(ListNode* head) {
// if (head == nullptr || head->next == nullptr) {
// return false;
// }
// ListNode* slow = head;
// ListNode* fast = head->next;
// while (slow != fast) {
// if (fast == nullptr || fast->next == nullptr) {
// return false;
// }
// slow = slow->next;
// fast = fast->next->next;
// }
// return true;
// }
// };
11-27
212
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-27
345
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-31
199
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-12
680
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)