首页 > 解决方案 > 检测链表中的循环,关于慢速和快速指针

问题描述

我的问题是为什么要检查 slow_ptr 和 fast_ptr 指针是否为 NULL 以查看是否存在循环,而我们只能通过检查 fast_ptr 是否为 NULL 来做到这一点,因为 fast_ptr 的移动速度比 slow_ptr 快。

代码链接:https ://www.geeksforgeeks.org/find-length-of-loop-in-linked-list/

int countNodesinLoop(struct Node *list)  
{  
    struct Node *slow_p = list, *fast_p = list;  

    //in this part
    while (slow_p && fast_p &&  
                     fast_p->next)  
    {  
        slow_p = slow_p->next;  
        fast_p = fast_p->next->next;  

        /* If slow_p and fast_p meet at  
        some point then there is a loop */
        if (slow_p == fast_p)  
            return countNodes(slow_p);  
    }  

    /* Return 0 to indeciate that  
       their is no loop*/
    return 0;  
}   

标签: linked-list

解决方案


推荐阅读