这题很简单,快慢指针就行了,一个pfast步长为2,一个pslow步长为1,若有环的话,pfast一定会等于pslow。无环,则肯定不会。
/**
* 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||head->next==NULL)return false;
ListNode* pfast=head;
ListNode* pslow=head;
while(pfast!=NULL&&pfast->next!=NULL){
pfast=pfast->next->next;
pslow=pslow->next;
if(pfast==pslow){
return true;
}
}
return false;
}
};LeetCode:Linked List Cycle,布布扣,bubuko.com
原文:http://blog.csdn.net/whu_sky/article/details/22748331