dimanche 8 décembre 2019

Error "Abort signal from abort(3) (sigabrt) " for linked list in C++

The following code is for a basic circular linked list, but when one inputs a large value for n(e.g 8 digits) it throws the "abort signal from abort(3) (sigabrt)" error. I'm not sure what it means and would love some guidance about fixing this with regard to my code. Thank you!

#include<bits/stdc++.h> 
using namespace std; 

//First I created a structure for a node in a circular linked list
struct Node 
{ 
    int data; 
    struct Node *next; 
}; 

// function to create a new node
Node *newNode(int data) 
{ 
Node *temporary = new Node; 
temporary->next = temporary; 
temporary->data = data; 
return temporary; 
} 

// This function finds the last man standing in
//the game of elimination
void gameOfElimination(int m, int n) 
{ 
    //first I created a circular linked list of the size which the user inputted 
    Node *head = newNode(1); 
    Node *prev = head; 
    //this loop links the previous node to the next node, and so on.
    for (int index = 2; index <= n; index++) 
    { 
        prev->next = newNode(index); 
        prev = prev->next; 
    } 
    prev->next = head; //This connects the last and first nodes in our linked list together. 

    //when only one node is left, which is our answer:
    Node *ptr1 = head, *ptr2 = head; 
    while (ptr1->next != ptr1) 
    { 

        int count = 1; 
        while (count != m) 
        { 
            ptr2 = ptr1; 
            ptr1 = ptr1->next; 
            count++; 
        } 

        /* Remove the m-th node */
        ptr2->next = ptr1->next; 
        ptr1 = ptr2->next; 
    } 

    printf ("%d\n ", 
            ptr1->data);
} 

//main program which takes in values and calls the function:
int main() 
{ 
    int n, p;
    cin>>n>>p;
    int m=p+1;
    gameOfElimination(m, n); 
    return 0; 
} 

Aucun commentaire:

Enregistrer un commentaire