Floyd's Algorithm - SIGTSTP error

123 Views Asked by At

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;
}
1

There are 1 best solutions below

4
On

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.