Leetcode exercise-(question number 141)

Given a linked list, determine whether there is a ring in the linked list.
In order to represent the rings in a given linked list, we use the integer pos to indicate the position where the end of the linked list is connected to the linked list (the index starts from 0). If pos is -1, then there is no ring in the linked list.
Source: LeetCode
Link: https://leetcode-cn.com/problems/linked-list-cycle

Problem-solving ideas: quick and slow pointers

bool hasCycle(struct ListNode *head) {
    
    
    struct ListNode *a =NULL,*b=NULL;
    if(head==NULL||head->next==NULL)
    return false;
    a=head,b=head->next;
    while(a!=b){
    
    
        if(b==NULL||b->next==NULL)
        return false;
        a=a->next;
        b=b->next->next;
    }
    return true;   
}

Guess you like

Origin blog.csdn.net/lthahaha/article/details/105499864