我有一个家庭作业,要求我从文本文件创建一个链接列表,有两个重要的警告!
没有数组
没有载体
真的,我对链接列表有一些了解,但我似乎在我的程序中某处失败了。通常,我得到这些ERROR代码就像无法访问traverse-> next Node一样。我经常检查traverse-> next节点以遍历我的链表。
现在,我没有收到任何错误代码。我在链表中有一个cout语句,告诉我遍历节点至少(在某一点上)等于我的文本文件的输出。它在while循环中显示正确的信息,但是当我去打印它时......信息消失了。
我最好的猜测是我的程序没有正确链接到我的列表。但是,如果是这样的话,我还无法弄清楚如何正确地链接它们。
有人可以给我一些提示或一些建议吗?它确实是作业的第一部分(因此" InitList()"函数名称),但我努力让它发挥作用。
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
struct Node
{
string fName;
string lName;
double hours;
double pay;
int unionCode;
int id;
Node *next;
}; Node *head = nullptr;
//standard node struct with a global root node so I don't have to pass it everytime
void InitList();
void AddRecord();
void PrintList();
//prototypes
int main()
{
InitList();
PrintList();
int options;
cout << "MENU\n" <<
"______________________________\n" <<
"1: Add a Record\n" <<
"2: Modify a Record\n" <<
"3: Display a Record\n" <<
"4: Display a Summary\n" <<
"5: Display File\n" <<
"6: Exit Program\n" << endl;
cin >> options;
switch (options)
{
case 1:
AddRecord();
break;
default:
break;
}
}
void AddRecord()
{
fstream file;
file.open("PATH.txt", ios::app);
file.close();
}
void InitList()
{
//initializes the linked list from here on out, all changes made are
//reflected on the list
//and the text doc until the program quits
fstream file;
file.open("PATH.txt");
Node *add;
Node *traverse = head; //set traverse pointing to head
while (file.good()) //I realize this isn't ideal, but it's temporary to get it working
{
add = new Node;
file >> add->fName
>> add->lName
>> add->id
>> add->pay
>> add->hours
>> add->unionCode;
add->next = nullptr;
if (traverse)
{
while (traverse->next)
{
traverse = traverse->next;
}
traverse->next = add;
cout << traverse->fName << endl;
}
else
{
head = add;
cout << head->fName << endl;
}
}
file.close();
}
//simple Printing function... this is that part that's printing out ONLY the head value and nothing else (hence my assumption that head isn't linked)
void PrintList()
{
Node *traverse = head;
while (traverse->next)
{
cout << traverse->fName << " " << traverse->lName << " " << traverse->id << " $" << traverse->pay << " " << traverse->hours << " " << traverse->unionCode << endl;
traverse = traverse->next;
}
}
答案 0 :(得分:0)
while (file.good())
{
Node *add = new Node;
file >> add->fName >> add->lName >> add->id >> add->pay >> add->hours >> add->unionCode;
add->next = nullptr;
InitList(add);
}
这就是我修复它的方法(代码位于INT MAIN()中)。基本上,我将数据传输到Node * add,然后将其传递给普通的linked_list添加功能。我通过引用传递它。有人可以解释为什么它以前不会工作吗?我猜测它与&#34; traverse&#34;的价值有关。没有被重置为&#34; head&#34;就像我以前一样。我怎么能解决这个问题?
在循环中创建链表时,最好是使用迭代函数并传递遍历,像我一样迭代函数,还是像I FAILED那样使用复杂的嵌套循环系统?