gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:53:18 24 4
gpt4 key购买 nike

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

#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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com