LeetCode 02.08. Loop detection

Original question link I
originally thought that it could be solved by the general operation of the linked list, but it didn't work after a lot of trials. The basic complexity I can think of is relatively high. The best answer in the topic comment is the method of speed pointer, but the description is not clear enough. Watching the video of the brother at station B, the toilet is opened.

Keep working hard, we all have a bright future!

Post the code:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    
    
public:
    ListNode *detectCycle(ListNode *head) {
    
    
        if(!head || !head->next) return NULL;
        ListNode *fast = head, *slow = head;
        while(fast){
    
    
            fast = fast->next;
            slow = slow->next;
            if(!fast) return NULL;
            else fast = fast->next;
            if(fast == slow) break;
        }
        if(!fast) return NULL;
        fast = head;
        while(fast != slow){
    
    
            fast = fast->next;
            slow = slow->next;
        }
        return fast;
    }
};

Guess you like

Origin blog.csdn.net/qq_43078427/article/details/109272973