如何从文件读入双链表

How to read from a file into a doubly linked list?

本文关键字:链表 从文件读      更新时间:2023-10-16

这是我在学校项目的一小部分。我已经将数据存储到一个文本文件中,格式如下:

bike
dock
car

现在,我想把这个文件中的数据读入一个双链表。这是我使用的代码。

#include <iostream>
#include <strings.h>
#include <fstream>
using namespace std;
class item
{
public:
    string name;
    item *next;
    item *previous;
};
class list:private item
{
    item * first;
public:
    list();
    void load();
    void display();
};
list::list()
{
    first = NULL;
}
void list::load()
{
    item *current;
    ifstream fin;
    fin.open("List.txt");
    current=new item;
    while(!fin.eof())
    {
        fin>>current->name;
        current->previous=NULL;
        current->next=NULL;
    }
    fin.close();
    first=current;
}

现在,问题是我无法将文件的每个单词存储到一个新节点中。这段代码将文件的最后一个单词存储到列表的第一个节点。我不知道该怎么做。我不太擅长链表。有人能帮我解决这个问题吗?

那么,试试这样的load函数(未测试):

void list::load()
{
    item *current;
    item *prev;
    ifstream fin;
    fin.open("List.txt");

    prev = NULL;
    while(!fin.eof())
    {
        current=new item;
        if (first == NULL) // we set first the first time
            first = current;
        fin>>current->name;
        current->previous=prev;
        current->next = NULL;
        if (prev != NULL)
            prev->next=current;
        prev = current; // we store the current as the prev for next iteration
    }
    fin.close();
}