给定一个链表,判断它是否有环。
样例
给出 -21->10->4->5, tail connects to node index 1,返回 true
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: True if it has a cycle, or false
*/
bool hasCycle(ListNode *head) {
// write your code here
return isCycle(head);
}
bool isCycle(ListNode* head)
{
if(head==NULL ||head->next==NULL) return false;
ListNode* fast=head;
ListNode* slow=head;
while(fast!=NULL&&fast->next!=NULL)
{
fast=fast->next->next;
slow=slow->next;
if(slow==fast)
return true;
}
return false;
}
};