如何从文件读入双链表
How to read from a file into a doubly linked list?
这是我在学校项目的一小部分。我已经将数据存储到一个文本文件中,格式如下:
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();
}
相关文章:
- constexpr 链表 - 从 const X* 到 X* 的转换无效
- 链表(从 'Node<int>*' 到 'int' 的转换无效 [-fallowive]|)
- C++ - 将数字表从文件读取到 2D 数组中(仅存储最后一行)
- C++ 它没有从文件读回动态结构
- 从文本文件将整数读入简单的链表中.然后对整数列表进行气泡排序并读出到另一个文件
- C++程序将链表从位置 m 反转到 n
- 从文件读入.多个分隔符?C++
- 从文件读入结构
- 用户定义的链表从函数返回指针
- 使用字符串函数将数据从文件读入结构
- 函数从文件读入向量c++
- 对一个双链表从低到高排序
- 将链表从原始指针转换为智能指针
- 从文件读到另一点c++
- 将链表从C传递到c++
- 如何从文件读入双链表
- 从文件读入到数组
- 从文件读入矢量
- 将数字从文件读入数组
- 将数据从文件读入结构体,对数据进行排序并写入文件