C++ solution


  • 0
    H
    class Solution {
    public:
        ListNode *detectCycle(ListNode *head) {
            if(!head || !head->next) return NULL;
            ListNode *fast = head, *slow = head;
            bool flag = false;
            while(fast && fast->next) {
                fast = fast->next->next;
                slow = slow->next;
                if(fast == slow) {
                    flag = true;
                    break;
                }
            }
            if(!flag) return NULL;
            ListNode *ans = head;
            while(ans != slow) {
                ans = ans->next;
                slow = slow->next;
            }
            return ans;
        }
    };
    

Log in to reply
 

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