Question

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

but the first element of the list is repeated and i can't see my error.

This my 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 = a->Forward) {

        std::cout << a->Current << std::endl;
    }

Edited here is my ListObject class

template <class LDT>
class ListObject {

public :

    ListObject* Back;
    LDT Current;
    ListObject* Forward;

    ListObject(const LDT& elem, ListObject&  _back, ListObject& _forward) {

        Back = &_back;
        Current = elem;
        Forward = &_forward;


    }

    ListObject() {
        Back = nullptr;
        Forward = nullptr;
    }

    ListObject(const ListObject& lista) {

        Back = 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;}
    }



};
Was it helpful?

Solution

Modify your else clause with :

ListObject<DT> *temp = Last;

Last = new ListObject<DT>(); Last->Back = temp; Last->Forward = nullptr; Last->Current = elem;
temp->Forward = Last;

This will fix your memory leak.

Replace also the if clause by :

if(First == nullptr) { //list is empty

        First = new ListObject();
        First->Current = elem;

        First->Back = nullptr;
        First->Forward = nullptr;

        Last = First; //last IS also first, do not duplicate

        return;
}

This will fix the duplicated first element.

OTHER TIPS

As Neil said, while adding the first item to the list, you are assigning the value to First and Last. IMHO the Last-Current should be nothing (null)

I believe the first item might be present only twice in the list.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top