Linked list C++

Linked list C++

本文关键字:C++ list Linked      更新时间:2023-10-16

我必须在链表的末尾添加一个节点,到目前为止它没有抛出任何错误,但显然它也不工作。我看过别人的答案,但看不出我的有什么问题。我认为问题可能是与getNext()和null。ps:我正在使用HPP

方法:

// ADD a node to the end of the Linked list
void add(const T& dado)
{
    Elemento < T > *novo = new Elemento<T>(dado, NULL);
    if (novo == NULL)
    {
        throw 2;
    }
    if (head->getNext() != NULL)
    {
        Elemento < T > *auxi = new Elemento<T>(dado, head->getNext());
        int i;
        for (i = 0; auxi->getNext() == NULL; i++)
        {
            auxi->setNext(auxi->getNext());
            if (auxi->getNext()() == NULL)
            {
                size++;
                auxi->setNext(novo);
            }
        }
    }
    else
    {
        size++;
        head->setNext(novo);
    }
}

我的元素类如下:

#ifndef ELEMENTO_HPP
#define ELEMENTO_HPP
template<typename T>
class Elemento {
 private:
    T *info;
    Elemento<T>* _next;
 public:
    Elemento(const T& info, Elemento<T>* next) : info(new T(info)), _next(next) {}
    ~Elemento() {
        delete info;
    }
    Elemento<T>* getNext() const     {
        return _next;
    }
    T getInfo() const {
        return *info;
    }
    void setNext(Elemento<T>* next) {
        _next = next;
    }
};
#endif

您可以在这里看到完整的代码:http://pastebin.com/7yJfsK8j(方法名称为葡萄牙语,但有注释需要解释)。

试试for-loop:

Elemento<T> *ptr;
//Will iterate until ptr-> getNext() is null (this means ptr is not null).
for(ptr = head; ptr -> getNext() != NULL; ptr = ptr -> getNext())
{
   //Does nothing.
};
ptr -> setNext(novo);
size++;

希望它能起作用!