查找链表中是否有环:分别定义一个快指针、慢指针;
移动指针,快指针每次走二步,慢指针每次走一步,途中若快指针先抵达尾部,那么no cycle;若快慢指针相遇,那么有环。
/**
* 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) {
if(head==NULL)
return 0; //no cycle
ListNode *fast=head;
ListNode *low=head;
while(fast!=NULL&&low!=NULL)
{
low=low->next; // low go 1 step
for(int i=1;i<3;i++) //fast go 2 steps
{
if(fast==NULL)
return 0;
else
fast=fast->next;
}
if(fast==low)
return 1;
}
return 0; //fast meet end of the link list, there is no cycle
}
};