0

I am working on a problem to find the number of nodes present in loop (if any) in the given linked list. Below is the function which accepts head of the node, checks for loop using Floyds cycle algorithm and if found, gives the number of nodes in loop. While running the program, it gives runtime error SIGTSTP, which as per my understanding is a signal that is passed when the program is to be stopped during execution, considering that, m not able to see what is to be changed in this code. On debugging the highlighted part seems to be the root cause of the issue.

Please throw some light on what SIGTSTP means and how to handle the same in C++.

int countNodesinLoop(struct Node *head)
{
    Node* slow = new Node;
    Node* fast = new Node;
    slow = head;
    fast = head;

    **do{
        if(slow==NULL || fast==NULL || fast->next==NULL)
            return 0;                            // LOOP NOT FOUND
        slow = slow->next;
        fast = fast->next;
        fast = fast->next;
    }while(slow!=head);**

    // LOOP FOUND
    slow = head;
    while(slow!=fast)
    {
        slow = slow->next;
        fast = fast->next;
    }                      
    // BOTH SLOW AND FAST POINT TO THE NODE WHERE LOOPS START
    int ans = 1;          // COUNTER
    slow = slow->next;                
    while(slow!=fast)
    {
        slow = slow->next;
        ans++;
     }
     return ans;
}
Ayush Pallav
  • 919
  • 9
  • 18

1 Answers1

0

I don't know why you're seeing SIGTSTP -- perhaps a timeout in a resource-constrained environment?

Check the loop condition in your first loop.

Separately, don't allocate empty nodes for slow and fast with new. Those are memory leaks.

j_random_hacker
  • 50,331
  • 10
  • 105
  • 169
  • I tried running the code without using "new". And the loop conditions seems okay to me. I have done dry run and it's working fine. – Ayush Pallav Jun 06 '18 at 11:33
  • @AyushPallav: Read the psuedocode on the Wikipedia page. – j_random_hacker Jun 06 '18 at 11:40
  • The loop runs till slow and fast meet at a same point. Logic is if it does, there is a loop. That is the case here. I cannot see any problem in that. – Ayush Pallav Jun 06 '18 at 12:17
  • All I can suggest is to keep staring at the loop condition in your code and in the Wikipedia pseudocode until you see what's different. Or take a break and come back. – j_random_hacker Jun 06 '18 at 12:20