Linked list C++
Linked list C++
我必须在链表的末尾添加一个节点,到目前为止它没有抛出任何错误,但显然它也不工作。我看过别人的答案,但看不出我的有什么问题。我认为问题可能是与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++;
希望它能起作用!
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 如何在 C 中正确使用 libiconv 使其不会报告"Arg list too long"?
- C++中带有List类的迭代器Segfault
- 使用"std::unordereded_map"映射到"std::list"对象
- GCC对可能有效的代码抛出init list生存期警告
- 使用std::list创建循环链表
- 重载Singly Linked List中的赋值运算符
- '[](std::list& list)<int>{return std::move(list)}(list)' 是否保证将 'list' 留空?
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?
- 为什么这个 std::queue/指向结构的指针列表直到 List.Size() == 0 才释放内存?
- "std::list::splice(std::const_iterator pos, std::list&& other)"是否保证将"其他"留空?
- 从嵌套循环中的 std::list 中删除将返回访问冲突
- QStringList vs list<shared_ptr<QString>> 性能比较C++
- 包含 std::list 的结构体的 C++ 初始化
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- C++ assigment std::list:<typename>:itrator 在 main 中工作,但在方法中它不起作用
- 在基于范围的 for 循环期间插入 std::list 的后面
- 循环挂起迭代的 std::擦除 on std::list
- 如何增加以前由新运算符分配的 C++ std::list 数组的大小?