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

时间:2012-11-07 19:50:36

标签: 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创建更多节点。他们必须为每个节点使用不同的名称吗?我看到我在哪里创建了一个名为root的新节点。我是否必须为每个节点执行此操作?如果我这样做,我可以让用户输入该节点的名称并让程序以该名称写入吗?

1 个答案:

答案 0 :(得分:1)

要通过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”。要查找任何一个节点,请从“root”开始并遍历到您想要的节点。当然,您可以将ptrs保存到某些节点以便更快地访问,但这将特定于特定应用程序。

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

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

用户输入一个值10次,但每次都是“临时”。所以它一直被覆盖。