c++ - 将新节点添加到列表并动态命名它

标签 c++ list linked-list

我有几个关于列表的问题。首先,这是我的代码:

#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”和“curr”。要找到任何一个节点,请从“根”开始并遍历到您想要的那个节点。当然,您可以将 ptrs 保存到某些节点以加快访问速度,但这将特定于特定应用程序。

同样在您当前的输入循环中:

for( int i=0; i<10; i++)//Will promt user to enter numbers
{
    cout << "Enter string name for new node: ";
    cin >> temp;
}

用户输入一个值 10 次,但每次都进入“temp”。所以它不断被覆盖。

关于c++ - 将新节点添加到列表并动态命名它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13277091/

相关文章:

c - 基于比较函数插入链表队列

c++ - 递归函数破坏一般树c++

list - 如何在 Terraform 0.12 中通过列表(对象)进行 for_each

java - 从编辑文本内容创建 RecyclerView 列表

c - 结构指针初始化错误

c - 在不移动数组元素的情况下使用下标对数组进行排序

c++ - 子进程完成时调用函数

C++:重新使用打印到控制台的行

c++ - 如何在 SWIG 中包装可变模板类的可变模板成员函数?

python - 获取嵌套字典中唯一值的列表(或集合)