/** * 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 *slowP = head; ListNode *fastP = head->next; while(slowP != fastP && fastP != NULL && fastP->next != NULL){ slowP = slowP->next; fastP = fastP->next->next; } if(slowP == fastP){ return true; } else { return false; } } };
原文地址:http://blog.csdn.net/wyj7260/article/details/39779263