给定一个链表,判断链表中是否有环。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
struct ListNode *fast, *slow;
if(head == NULL || head -> next == NULL)
return false;
slow = head;
fast = head -> next;
while(slow != fast){
if(fast == NULL || fast -> next == NULL)
return false;
slow = slow -> next;
fast = fast -> next -> next;
}
return true;
}