[英]Linked list C++
I have to ADD a node to the end of a Linked LIST, it's not throwing any errors so far, but apparently it's not working too.我必须在链接列表的末尾添加一个节点,到目前为止它没有抛出任何错误,但显然它也不起作用。 I've looked into others answers, but couldn't see what's wrong with mine.
我查看了其他答案,但看不出我的有什么问题。 I think that the problem might be with getNext() and NULLs.
我认为问题可能出在 getNext() 和 NULLs 上。 ps: I'm using HPP
ps:我用的是HPP
Here's the method :这是方法:
// 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);
}
}
My elemento class is as follow:我的元素类如下:
#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
You can see the whole code here: http://pastebin.com/7yJfsK8j (method names in Portuguese, but there are comments to explain).你可以在这里看到完整的代码: http : //pastebin.com/7yJfsK8j (葡萄牙语的方法名称,但有注释解释)。
Try this for-loop:试试这个 for 循环:
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++;
Hope it works!希望它有效!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.