首页 > 代码库 > leetcode Linked List Cycle

leetcode Linked List 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 || 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;
      }
    }
};

leetcode Linked List Cycle