将新节点添加到列表中并动态命名

Adding a new node to a list and dynamically naming it

本文关键字:列表 动态 添加 新节点 节点      更新时间:2023-10-16

我有一些有关列表的问题。首先,这是我的代码:

#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次,但每次都会输入"温度"。因此,它不断被覆盖。