方法一:快慢指针

    1. /**
    2. * Definition for singly-linked list.
    3. * struct ListNode {
    4. * int val;
    5. * ListNode *next;
    6. * ListNode(int x) : val(x), next(NULL) {}
    7. * };
    8. */
    9. class Solution {
    10. public:
    11. bool hasCycle(ListNode *head) {
    12. if(head==NULL||head->next==0){
    13. return false;
    14. }
    15. ListNode *slow=head;
    16. ListNode *fast=head;
    17. while(fast){
    18. slow=slow->next;
    19. if(fast->next){
    20. fast=fast->next->next;
    21. }else{
    22. return false;
    23. }
    24. if(slow==fast){
    25. return true;
    26. }
    27. }
    28. return false;
    29. }
    30. };