我正在尝试为for循环内的链表生成节点。我已经定义了头,尾和临时节点(用于存储数据)的节点。但是,当我将它包含在for循环中并打印结果时,它不会返回任何内容。关于如何改进代码的任何建议?
private:
Node *head;
Node *tail;
};
最佳答案
如果要创建100个节点的列表,则需要分配100个节点,而不仅仅是一个。像这样在循环内移动new Node
void createNode(int value)
{
for (int i = 0; i<100; i++) {
node *temp = new Node;
temp->data = i;
temp->next = nullptr;
if (head == nullptr)
{
head = temp;
tail = temp;
}
else
{
tail->next = temp;
tail = temp;
}
}
当然,在名为
createNode
的函数中分配100个节点也不是一个好主意,但是我想您只是在做实验。
关于c++ - 在C++中的for循环内为链表生成节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61438939/