在链接列表中添加数据
Adding data in a linked list
我刚开始学习链表,我正试图从文件中提取某些信息,并使用推送功能将其插入链表。当我试图查看信息以查看它是否正确插入时,它只是一遍又一遍地显示信息的最后一行。我做错了什么?这是我的代码:
struct Country
{
string name;
double population;
};
struct Node
{
Country ctry;
Node *next;
};
Node *world;
void push(Node *&world);
int main ()
{
push(world);
return 0;
}
void push(Node *&world)
{
ifstream inFile("file.csv");
if (!inFile.fail())
{
cout << "File has opened successfully." << endl;
}
if (inFile.fail())
{
cout << "File has failed to open." << endl;
exit(1);
}
double temp, temp1, temp2, temp3, population;
string countryName;
Node *top = new Node;
for (int i = 0; i < 300; i++)
{
if (inFile.eof())
{
top->next = NULL;
break;
}
inFile >> temp >> temp1 >> temp2 >> temp3 >> population;
getline (inFile,countryName);
top -> ctry.population = population;
top -> next = world;
world = top;
top -> ctry.name = countryName;
top -> next = world;
world = top;
}
for (int j = 0; j < 5; j++)
{
cout << top -> ctry.name << endl;
top -> next;
}
}
"world"是链接列表的开始。
Node *top = new Node;
您在此处创建了一个新节点。我将跳过您填充内容的部分。
top -> next = world;
world = top;
正如我提到的,"world"是指向列表开头的当前指针。您现在将其保存在顶部的next
中。然后将world
设置为指向新节点。这成为了你列表的新开始。这很好。
top -> next = world;
world = top;
你不小心重复了几行代码。由于此时"top"与"world"是相同的指针,因此只需将列表顶部的节点设置为指向自身即可。这是你的无限循环。
您只为一个Node top分配内存,并一直使用它。在for循环中放入以下行以解决您的问题:
Node *top = new Node;
我看到您的代码有一些问题。
首先,这条线没有任何作用:
top -> next;
如果你正在遍历一个链表来读取存储的值,你可能会想做一些类似以下的事情:
for (;;)
{
cout << world -> ctry.name << endl;
if (world->next == null) break;
else world = world -> next;
}
在你的创建循环中,你有两条重复的线和圆形链接:
top -> next = world;
world = top;
top -> ctry.name = countryName;
top -> next = world;
world = top;
我想这就是你想要做的:
world = top;
for (int i = 0; i < 300; i++)
{
if (inFile.eof())
{
top->next = NULL;
break;
} else top = top -> next;
inFile >> temp >> temp1 >> temp2 >> temp3 >> population;
getline (inFile,countryName);
top -> ctry.population = population;
top -> ctry.name = countryName;
top -> next = new Node;
}
最后,为自己保存一个函数调用并使用其他:
if (!inFile.fail())
{
cout << "File has opened successfully." << endl;
} else {
cout << "File has failed to open." << endl;
exit(1);
}
我希望这能帮助你走上正轨。
相关文章:
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 如何使用 Google Test 向测试添加元数据 / 如何将数据从 Google Test 发送到 TestEven
- 将私有数据成员添加到野牛生成的类中
- 可变参数模板与使用元组在参数中添加不同的数据对
- 在PROGMEM中添加更多数据会中断Arduino Mega 2560上的SPI传输
- 在 2D 矢量数组中的特定标头下添加数据
- 使用模板参数添加数据
- 如何在结构中动态添加数据,这是指向指针数组的指针
- 如何在数组 QT C++中添加数据
- 插入时对对象进行排序(若存在,则添加数据)
- 在链接列表中添加数据
- 使用python解析或读取CPP文件,并通过忽略CPP文件注释来添加数据
- 跟踪何时为增强序列化添加数据成员
- 如何在c++中使用单链表对象显示和添加数据
- 在c++中向结构体addrinfo中添加数据
- 从另一个基类向结构体添加数据成员
- 如何添加数据到椭圆QT
- 写波头和添加数据,不关闭流
- 使用c++检查和添加数据到protobuff中
- 如何在c++中添加数据结构到动态链接库