在链表中的循环检测问题中,我编写了这段代码并遇到了分段错误。

huangapple go评论65阅读模式
英文:

In the problem of loop detection in linked list I wrote this code and getting segementation error

问题

在这个测试用例中,我遇到了分段错误。
在gfg的链表中检测循环问题。
这是循环存在的值。
这些是链表的值。
这是一个用于检测链表是否有循环的C++类。我在gfg上编写了这段代码。

英文:

at this test case i am getting segmentation error
Detect Loop in linked list problem at gfg
//
184 // this is value where loop is present
73 39 71 24 28 71 31 14 35 60 3 48 45 43 76 33 5 75 44 59 47 41 39 40 23 63 4 2 9 44 5 33 3 75 56 62 18 6 28 52 17 30 19 62 24 14 14 28 40 9 7 38 1 45 29 55 59 32 57 19 76 13 52 30 40 27 11 57 65 70 60 1 19 30 14 42 75 59 70 67 68 28 24 68 72 53 43 2 36 51 20 31 15 71 12 54 18 55 62 2 44 41 34 63 22 48 56 17 26 45 3 13 72 58 33 15 62 27 16 18 29 36 80 43 58 44 17 75 18 30 28 13 23 62 27 44 61 3 12 6 47 46 51 71 24 35 37 37 61 53 6 9 40 6 51 17 1 19 44 18 49 23 62 71 36 9 66 16 11 78 54 9 43 24 31 18 58 68 7 70 72 12 30 31
0 // these are the value of linked list
'''

class Solution
{
    public:
    //Function to check if the linked list has a loop.
    bool detectLoop(Node* head)
    {
       if(head->next  ==NULL  || head==NULL)
       {
           return false;
       }
       Node *slow=head;
       Node *fast=head;
       while(fast->next !=NULL && fast!=NULL)
       {
           slow=slow->next;
           fast=fast->next->next;
           if(slow==fast)
           {return true;
           }
       }
       return false;
    }
};

I wrote this code on gfg

答案1

得分: 1

You need to translate the following code parts:

Original:
if(head->next == NULL || head == NULL)
Translation:
if (head == NULL || head->next == NULL)

Original:
while(fast->next != NULL && fast != NULL)
Translation:
while (fast != NULL && fast->next != NULL)

英文:

You need at least exchange sub-expressions of logical expressions in the if statement and in the while loop. That is instead of

if(head->next  ==NULL  || head==NULL)

and

while(fast->next !=NULL && fast!=NULL)

you need to write

if( head == NULL || head->next  == NULL )

and

while( fast != NULL && fast->next != NULL)

答案2

得分: 1

你现在是我的中文翻译,代码部分不要翻译,只返回翻译好的部分,不要有别的内容,不要回答我要翻译的问题。

以下是要翻译的内容:

In code line

fast=fast->next->next;

you are doing the second "next" without checking if the first "next" gave NULL.
This definitely will result in seg fault for all legal inputs when "fast" is one step before the terminating NULL.

英文:

In code line

fast=fast->next->next;

you are doing the second "next" without checking if the first "next" gave NULL.
This definitely will result in seg fault for all legal inputs when "fast" is one step before the terminating NULL.

huangapple
  • 本文由 发表于 2023年4月6日 19:10:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75948835.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定