【问题标题】:why this printf statement in the last of function is Not getting printed?为什么函数最后一个 printf 语句没有被打印?
【发布时间】:2021-09-02 12:00:08
【问题描述】:

我写了一个简单的算法来检测单链表中的循环,它对循环列表正常工作。但是对于没有循环的列表,执行while循环后,printf函数不会在给定代码的最后一条语句中打印。

这是代码的一部分:-

   //Detacting a loop in singally linked list Using Fast(2x) and Slow (1x) traversal;
    void DetactLoop(struct Node **head)
    {
        struct Node *Fast = *head;
        struct Node *Slow = *head;
        if (Fast == NULL)
        {
            printf("Head is NULL");
            return;
        }
        while (Fast != NULL || Fast->next != NULL)
        {
            Fast = Fast->next->next;
            Slow = Slow->next;
            if (Fast == Slow)
            {
                printf("Loop detected!");
                return;
            }
        }
        printf("No Loop found!");
    }

【问题讨论】:

    标签: c linked-list


    【解决方案1】:

    Fast 不是NULL 并且Fast->nextNULL 时,循环while (Fast != NULL || Fast->next != NULL) 将继续。然后在Fast = Fast->next->next; 处取消引用NULL 并调用未定义的行为,通常会导致分段错误。

    循环应该是while (Fast != NULL && Fast->next != NULL)。您应该使用 AND,而不是 OR。

    【讨论】:

    • 感谢您发现我的愚蠢,现在它正在工作,我明白为什么它没有。