Why this code fails?

  • 0
    class Solution {
        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;
            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

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

  • 0

    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

    I also encounter this problem. Haha!

  • 0
    This post is deleted!

Log in to reply

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