重复(自定义)双向链表的第一个元素

时间:2013-08-26 06:10:54

标签: c++ doubly-linked-list

我需要为数据结构课程制作一个自定义的双向链表。

但重复列表的第一个元素,我看不到我的错误。

这是我的push_back函数:

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;

    }

}

主要

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

这里编辑的是我的ListObject类

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



};

2 个答案:

答案 0 :(得分:1)

使用以下命令修改您的else子句:

ListObject<DT> *temp = Last;

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

这将解决您的内存泄漏问题。

将if子句替换为:

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

这将修复重复的第一个元素。

答案 1 :(得分:1)

正如Neil所说,在将第一项添加到列表中时,您将值分配给First和Last。恕我直言,Last-Current应该没什么(null)

我相信第一项可能只在列表中出现两次。