我试图使用 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;
学习值(value)的一部分,只是坚持 std::forward_list
或 std::list
,而不是列表。或者甚至更好地使用 std::vector
或其他容器(取决于您对容器的用途)。
关于c++ - 使用 For 循环创建链表 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31443533/