c++ - The first element of a ( custom ) doubly linked list is repeated -


i need make custom doubly linked list course of data structures.

but first element of list repeated , can't see error.

this push_back function :

template <class dt> void list<dt>::push_back(const dt& elem) {      if(first->back == nullptr && first->forward == nullptr) {          first->current = elem;           last->current = elem;         last->back = first;          first->forward = last;          return;     } else {           listobject<dt> *temp = new listobject<dt>(*last);          last = new listobject<dt>(); last->back = temp; last->forward = nullptr; last->current = elem;         temp->back->forward = temp;         temp->forward = last;      }  } 

the main

list<int> c;      c.push_back(66);     c.push_back(44);     c.push_back(88);     c.push_back(58);      std::cout << "---------------------------" << std::endl;     for(listobject<int> *a = c.first; a; = a->forward) {          std::cout << a->current << std::endl;     } 

edited here listobject class

template <class ldt> class listobject {  public :      listobject* back;     ldt current;     listobject* forward;      listobject(const ldt& elem, listobject&  _back, listobject& _forward) {          = &_back;         current = elem;         forward = &_forward;       }      listobject() {         = nullptr;         forward = nullptr;     }      listobject(const listobject& lista) {          = lista.back;         current = lista.current;         forward = lista.forward;     }      ~listobject() {          delete back;         delete forward;         current;     }      listobject<ldt> makelist(const ldt& elem, listobject&  _back, listobject& _forward) {          return  listobject<ldt>::listobject(elem, _back, _forward);     }      void assing(ldt elem) {          current = elem;      }      bool hasforward() {          if(forward != nullptr) {return true;} else{return false;}     }    }; 

modify else clause :

listobject<dt> *temp = last;  last = new listobject<dt>(); last->back = temp; last->forward = nullptr; last->current = elem; temp->forward = last; 

this fix memory leak.

replace if clause :

if(first == nullptr) { //list empty          first = new listobject();         first->current = elem;          first->back = nullptr;         first->forward = nullptr;          last = first; //last first, not duplicate          return; } 

this fix duplicated first element.


Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -