lundi 20 avril 2020

Why do I get a segmentation fault here?

void LinkedList<T>::mergeSort(Node*& curr) {
    if(curr->next!=nullptr)
    {
      Node* ptr1;
      Node* ptr2=curr;
 //splits linked list
    for(int i=0;i<getLength()/2;i++)
     {
       ptr1=ptr2;
       ptr2=ptr2->next;
     }
      ptr1->next=nullptr;
      ptr1=curr;
  //recursive call for sorting
      mergeSort(ptr1);
      mergeSort(ptr2);
  //merge lists back together
      if(ptr1==nullptr)
         curr=ptr2
      else if(ptr2==nullptr)
         curr=ptr1

       Node* reff=ptr1;

     while(reff->next !=nullptr)
     {
     reff=reff->next;
     }
     reff->next=ptr2;

      curr=reff;
      }
   }

Everything seems to be working, expect this function. I always get a segmentation error and I'm confused why it happens. Also, I'm in college so there might be a more efficient way but this is the way I can do it, without looking ahead into the course.

Aucun commentaire:

Enregistrer un commentaire