Why this code fails?


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

    the idea is to use two pointers: slow and fast. The slow moves in the list one by one while the fast moves by skipping a node each time. If there is a cycle, eventually the fast and slow will meet each other.

    But this code fails. Can anyone help?


  • 1
    0

    Please change your code like this while (fast && fast->next)


  • 0
    M

    As this answer says, in cases with an odd number of nodes and no cycle, fast will eventually be a null node. When that happens, your while loop will attempt to find a property in a null object, giving a runtime error. Check fast in the while before checking fast->next.


  • 0
    K

    I also encounter this problem. Haha!


  • 0
    Y
    This post is deleted!

Log in to reply
 

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