There are some problems in my solution, but i don't know why, help.


  • 0
    G
        class Solution {
        public:
            bool hasCycle(ListNode *head) {
                if(!head)
                    return false;
                ListNode *slow, *fast;
                slow = fast = head;
                while(slow->next != NULL && fast->next->next != NULL){
                    slow = slow->next;
                    fast = fast->next->next;
                    if(slow == fast){
                        return true;                
                    }
                }
                return false;
            }
        };

  • 0
    G

    I know the problem, in the while statement, if the "fast->next" is null, then the "fats->next->next" will occurs error, so we just need to change the statement "slow->next != NULL" to "fast->next !=NULL", it will be right.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.