将新节点添加到列表中并动态命名
Adding a new node to a list and dynamically naming it
我有一些有关列表的问题。首先,这是我的代码:
#include <iomanip>
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
struct node {
int x;
node *next;
};
void main()
{
node *root;
node *curr;
int exit = 0;
string temp;
root = new node;
root->next = 0;
curr = root;
cout << "Please enter the root number: ";
cin >> root->x;
for( int i=0; i<10; i++)//Will promt user to enter numbers
{
cout << "Enter string name for new node: ";
cin >> temp;
}
if (curr != 0)//Used for traversing the LL and outputting
{
while (curr->next != 0)
{
cout << curr->x;
curr = curr->next;
}
}
}
我希望提示用户在第一个节点中输入for循环中的数字。但是我对创建更多节点的根源感到困惑。他们必须为每个节点带有不同的名称吗?我看到我在哪里创建了一个名为root的新节点。我必须为每个节点做到这一点吗?如果我这样做,我可以让用户输入该节点的名称并以该名称写入程序?
要通过根部创建更多节点,只需做同样的事情:
// assuming 'curr' points to end of list
curr->next = new node; // here's the new node
curr = curr->next; // update curr (if you want) to point to the newest node
curr->next = 0; // probably should be done in nodes ctor
您不会"命名"新节点,只有" root"answers" curr"。要找到任何一个节点,请从" root"开始,然后遍历您想要的一个节点。当然,您可以将PTR保存到某些节点,以更快地访问,但这是特定应用程序的特定访问。
也在您当前的输入循环中:
for( int i=0; i<10; i++)//Will promt user to enter numbers
{
cout << "Enter string name for new node: ";
cin >> temp;
}
用户输入一个值10次,但每次都会输入"温度"。因此,它不断被覆盖。
相关文章:
- 访问动态分配列表中的元素
- 动态分配列表 - 创建一个函数,用于删除所有包含偶数值的元素
- 基于数组的列表 - 动态数组创建时出错
- 动态填充的组合框不显示文本,列表未定义
- 使用列表进行动态结构分配
- 通过动态分配插入列表元素
- 尝试创建排序的动态列表(数据结构)
- C++ - 使用类中的初始值设定项列表初始化动态集
- 如何删除列表中的动态分配类对象<T>?
- C 使用链接列表和动态数组
- "Debug assertion failed" 这种有什么问题?它应该按年份对包含电影对象的动态列表进行排序
- 使用动态内存从向前列表中泄漏
- STL和元素插入中列表的动态分配
- 如何在C 中使用类创建动态列表
- 为什么动态分配的数组不能从列表初始值设定项推断其大小
- 如何在C++中创建动态对象列表
- 初始化C++初始值设定项列表中的动态 C 数组
- 初始化哈希表的 stl 列表动态数组(单独链接)
- 从置换的解析器表达式列表动态生成Spirit解析器表达式(在运行时)
- 当为将被放入数组中的字符串列表动态分配内存时,是否可以在程序的稍后添加到该列表中