给定一个链表,判断它是否有环。
样例
给出 -21->10->4->5, tail connects to node index 1,返回 true
思想:利用快慢指针,如果有环,则快慢指针最终会相等(fast==slow),如果没环,fast指针最终等于NULL
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
//利用快慢指针,如果里面存在环,则fast一定在环中循环,数圈后等于slow
ListNode *slow=head,*fast=head;
if(head==NULL||head->next==NULL)
return false;
while(fast!=NULL&&fast->next!=NULL)
{ slow=slow->next;
fast=fast->next->next;
if(slow==fast)
return true;
}
return false;
}
};