给定一个链表,判断它是否有环。
样例
给出 -21->10->4->5, tail connects to node index 1,返回 true
挑战
不要使用额外的空间
/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head||!head->next)
return false;
ListNode *fast=head;
ListNode *slow=head;
while(fast){
fast=fast->next;
if(!fast)
return false;
fast=fast->next;
slow=slow->next;
if(slow==fast)
return true;
}
return false;
}
};