c++ - 使用 For 循环创建链表 (c++)

标签 c++ for-loop linked-list new-operator

我试图使用 for 循环创建一个链表,但是 create() 方法中 for 循环中的“new”并没有完全分配一个新槽来存储新数据。结果,当我尝试打印列表时,出现了无限循环。有人可以告诉我这里出了什么问题吗?

struct node
{
    double value;
    node * next_ptr;
    node(){}
    node(double val, node * p): value(val), next_ptr(p) {}
    ~node(){}

};

node * create()
{
    using namespace std;
    node temp = {0, nullptr};
    node * result;
    for(int i=1; i<5; ++i)
    {
        result = new node;
        result->value = i;
        result->next_ptr = &temp;
        temp = *result;
    }
    return result;
};

最佳答案

你可能得到一个无限循环的原因是因为:

temp = *result;

您正在将 *result 的值复制到类型为 node 的新对象中,该对象与您创建的对象无关。

你想要做的是存储一个指针:

node* temp = nullptr;
node* result;
for(int i=0; i<5; ++i)
{
    result = new node;
    result->value = i;
    result->next_ptr = temp;
    temp = result;
}
return result;

Live demo


学习值(value)的一部分,只是坚持 std::forward_liststd::list,而不是列表。或者甚至更好地使用 std::vector 或其他容器(取决于您对容器的用途)。

关于c++ - 使用 For 循环创建链表 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31443533/

相关文章:

Java链表查找和删除方法

c++ - 如何将 boost python 列表转换为 PyObject

c++ - 如何退出单圈 `for` 循环?

java - 优化:用ListIterator替换for循环

java - LinkedList vs ArrayList - 询问实现思路的观点

python - 为 Linked-List 类实现递归 Add 方法时遇到问题

c++ - 整合功能

c++ - 使用 SDL2 和 OpenGL 使用 SDL TTF 显示文本

c++ - 使用 Rcpp::IntegerVectors 添加 int

Javascript 在 for 循环中设置超时函数