双指针

  • 当快慢指针能够相遇时,说明有环
  • 如果 fast 或者 fast->next 为NULL时,说明链表无环
    class Solution {
    public:
      bool hasCycle(ListNode *head) {
          // 空链表或者下一个结点为空
          if(!head || !head->next)
              return false;
          ListNode *slow = head,*fast = head->next;
          while(fast && fast->next){
              if(fast == slow)
                  return true;
              else{
                  fast = fast->next->next;
                  slow = slow->next;
              }
          }
          return false;
      }
    };