Привет Я работал над домашней работой, в которой я должен создать программу со связанным списком, которая может сохранять и восстанавливать свои данные из текстового файла. Я получил большую часть его работы, но у меня есть некоторые проблемы с восстановлением связанного списка, используя данные из текстового файла, который был создан из него. Когда я его восстанавливаю, последний элемент повторяется дважды. Я полагаю, что это как-то связано с циклом, но я не уверен, что включаю весь объем своего задания.
Ниже приведен код программы, которую я написал до сих пор:
ListNode.h
#pragma once
template<class T> class List;
template<class T>
class ListNode
{
friend class List<T>;
public:
ListNode(const T&);
T getData()const;
private:
T data;
ListNode<T>*next;
};//end ListNode class
template<class T>
ListNode<T>::ListNode( const T &info):data(info), next(NULL)
{
}//end default constructor
template<class T>
T ListNode<T>::getData()const
{
return data;
}//end function getData
list.h
#pragma once
#include<iostream>
#include <fstream>
using namespace :: std;
#include "ListNode.h"
template<class T>
class List
{
private:
ListNode<T> *head;
int size;
ListNode<T> *find(int index) const;
public:
List();
List(const List<T> &aList);
~List();
int getLength() const;
void insert (int index, T tempData);
void remove(int index);
void retrieve(int index, T &tempData);
bool isEmpty() const;
void print() const;
void save();
void restore();
};//end List class
Сломанная функция:
template <class T>
void List<T>::restore()
{
ifstream inFile;
inFile.open("listFile.txt");
T value=0;
int index, check =0;
cout << "Now reading the data from the text file..." << endl;
//inFile >> value;
//cout << "Value is : " << value << endl;
while (inFile != NULL)
{
inFile >> value;
index = getLength();
cout << value << endl;
insert(index+1, value);
inFile.close();
}
} // end function restore
Данные связанного списка, которые были сохранены в текстовом файле во время теста, были:
35
45
55
65
Когда связанный список был восстановлен из текстового файла, это было его содержание:
35
45
55
65
65
Как я могу решить эту проблему?