/**
* Index: 141
* Title: Linked List Cycle
* Author: ltree98
**/
题意
判断链表是否有环
我的
思路
快慢指针
时间复杂度: O(n)
空间复杂度: O(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) {
ListNode* slow = head;
ListNode* fast = head;
while(fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
if(slow == fast)
return true;
}
return false;
}
};