vendredi 3 mai 2019

Segmentation fault in insert(), doubly linked list on c++

I am trying to implement a doubly linked list in c++, but I get an error when I try to implement an insert() function. This is the struct of the Node:

struct NodoLDL
{
   T dato;
   NodoLDL *anterior;
   NodoLDL *siguiente;

   NodoLDL(const T &elem, NodoLDL *ant = nullptr, NodoLDL *sig = nullptr):
      dato(elem),
      anterior(ant),
      siguiente(sig)
   {}
};

And this is the list class:

 template <typename T>
class LDL
{
private:
   #include "nodoldl.h"
   size_t listSize;
   NodoLDL *listFront; //head
   NodoLDL *listBack; //tail

public:
   LDL() : listSize(0), listFront(nullptr), listBack(nullptr)
   {}
   void insert(size_t position, const T &elem);
(. . .)
}

This is the insert() function I am using, but I get segmentation fault on "temp2->anterior = temp3"

template<typename T>
void LDL<T>::insert(size_t position, const T &elem)
{    
    if(empty()){

        listFront = new NodoLDL(elem); 
        listBack = listFront;
        listSize+=1;

    }else if(listSize>0 && position==0){ //push_front()

        //The implementation for push_front() works fine.

    }else if(position==listSize){ //push_back()

        //The implementation for push_back() also works fine.           

    }else if(position > 0 && position<listSize){

        NodoLDL *temp1, *temp2, *temp3;
        temp1 = listFront;

        for(size_t i=0; i<position; i++){
            temp1 = temp1->siguiente;
        }

        temp2 = temp1->siguiente;
        temp3 = new NodoLDL (elem);
        temp1 -> siguiente = temp3;
        temp3 -> anterior = temp1;
        temp3 -> siguiente = temp2;
        temp2 -> anterior = temp3;

        listSize+=1;

    }else if(position > listSize){
        throw invalid_argument("insert() on invalid position");
    }
}

Insert at the beginning and at the end works, but it doesn't if I insert in the middle of the list, how can I fix it? Why is that logic wrong? I am not sure if it is only that line or all the logic in else if(position>0 && position<listSize) is incorrect.

Aucun commentaire:

Enregistrer un commentaire