【问题标题】:How to read from a file into a doubly linked list?如何从文件读入双向链表?
【发布时间】:2015-11-17 12:46:14
【问题描述】:

这是我在学校项目的一小部分。我已将我的数据以这种形式存储到一个文本文件中:

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

现在,问题是我无法将文件的每个单词都存储到新节点中。此代码将文件的最后一个单词存储到列表的第一个节点。我不知道该怎么做。我在链表中​​不是那么好。谁能帮我解决这个问题?

【问题讨论】:

  • 您在循环外只分配了一个带有new 的项目。您应该为从文件中读取的每个单词分配一个新项目。
  • 有什么理由不使用std::list
  • 你试图一次做太多事情。在担心文件 I/O 之前,您应该尝试从硬编码数据构建一个列表。
  • 您在循环之外执行new item,因此您只能在列表中获得一个节点。另外,使用while(!fin.eof)almost always the wrong way
  • 我还在学习 C++。我们的老师刚开始教我们链表。我们没有学到任何关于 std::list 的知识。这就是我不使用它的原因。

标签: c++ file doubly-linked-list


【解决方案1】:

好吧,试试这样的加载功能(未测试):

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

【讨论】:

  • (prev != NULL) 应该设置 prev->next,而 current->previous 将始终 = prev(即使它为 NULL)
  • 进行更改后它工作了。问题是我实际上是在一个没有文本文件的新项目中测试示例代码。因此,它没有要加载的文件。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2012-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-28
  • 1970-01-01
  • 2018-11-04
相关资源
最近更新 更多