在链接列表中添加数据

Adding data in a linked list

本文关键字:添加 数据 列表 链接      更新时间:2023-10-16

我刚开始学习链表,我正试图从文件中提取某些信息,并使用推送功能将其插入链表。当我试图查看信息以查看它是否正确插入时,它只是一遍又一遍地显示信息的最后一行。我做错了什么?这是我的代码:

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);
}

我希望这能帮助你走上正轨。