如何从文件中读入双向链表?
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;
}
现在,问题是我无法将文件的每个单词存储到一个新节点中。此代码将文件的最后一个单词存储到列表的第一个节点。我不知道该怎么做。我在链接列表中不是那么好。谁能帮我解决这个问题?
好吧,为加载函数尝试这样的事情(未测试):
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();
}
这是我在学校的项目的一小部分。我已将我的数据以这种形式存储到文本文件中:
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;
}
现在,问题是我无法将文件的每个单词存储到一个新节点中。此代码将文件的最后一个单词存储到列表的第一个节点。我不知道该怎么做。我在链接列表中不是那么好。谁能帮我解决这个问题?
好吧,为加载函数尝试这样的事情(未测试):
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();
}