Share my C++ solution,easy to understand


  • 5
    V
    /**
     * 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 *fast = head, *slow = head;
            
            while (fast != NULL && fast->next != NULL)
            {
                fast = fast->next->next;
                slow = slow->next;
                
                if (fast == slow)
                    return true;
            }
            
            return false;
        }
    };

  • 0
    H

    Please tell me why my code is wrong.

    class Solution {
    public:
    bool hasCycle(ListNode *head) {
        ListNode *s=head;
        ListNode *f=head;
        if(head==NULL)
                return 0;
        do
        {
                if(f->next==NULL||f==NULL)
                        return 0;
                s=s->next;
                f=f->next->next;
        }
        while(s!=f);
        return 1;
    }
    };

  • 0
    V

    Consider this situation:a->b->NULL.
    After the first loop,s point to b,f=NULL,then execute the judgment f->next ==NULL,error occurs because of null pointer dereference.


  • 0
    V

    you can try:if (f == NULL || f->next == NULL) return 0;


  • 0
    H

    Thank you :)


  • 0
    V

    anytime my friend :)


Log in to reply
 

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