繁体   English   中英

为什么最后一个函数中的这个 printf 语句没有被打印?

[英]why this printf statement in the last of function is Not getting printed?

我写了一个简单的算法来检测单链表中的循环,它对循环列表工作正常。 但是在没有循环的列表的情况下,执行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!");
    }

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM