Ring list notes (for personal use)

circular linked list

insert image description here
insert image description here
insert image description here
In any case, slow can walk half a circle at most, and
the fast and slow pointers take one step in slow, and two steps in fast are the most appropriate, because assuming that the difference between fast and slow is n every time they move forward, there will be a difference of n-1 steps, so they will definitely meet, if If it is a circular linked list.
the code

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
bool hasCycle(struct ListNode *head) {
    
    
    struct ListNode *fast=head;
    struct ListNode *slow=head;
    while(fast && fast->next)
    {
    
    
        slow=slow->next;
        fast=fast->next->next;
        if(fast == slow)
        {
    
    
            return true;
        }
    }
    return false;
}

Notes for personal use, the quality of the article is not good! ! !

Guess you like

Origin blog.csdn.net/2301_76895050/article/details/132371357