我仍然无法弄清楚如何跟踪我的链接列表但是已经取得了一些进展。
我的代码是通过节点完美地从文本文件中读取数据,但我似乎无法弄清楚如何将其正确地传输到show函数以显示所有节点。
从文件中读取(无法正常工作)
void insertAsFirstElement(ifstream& budgetFile, budgetItem *&head, budgetItem *&last, int number, int& counter)
{
int ctype;
string cname;
double camount;
char clearOrNot;
while (!budgetFile.eof())
{
budgetItem *temp = new budgetItem;
budgetFile >> ctype >> cname >> camount >> clearOrNot;
temp->theType = ctype;
cout << temp->theType << endl;
//cout << ctype << endl;
temp->name = cname;
cout << temp->name << endl;
temp->amount = camount;
cout << temp->amount << endl;
if (clearOrNot == 'Y')
{
temp->cleared = true;
}
else
{
temp->cleared = false;
}
last = temp;
temp->next = NULL;
if (counter == 0)
{
//head = temp;
head = temp;
}
counter++;
}
}
显示节点中的数据(只显示一个节点的数据......)*我需要显示所有节点及其所有数据。(必须与阅读有关)
void showList(budgetItem *current)
{
if (isEmpty(current)) {
cout << "The list is empty." << endl;
}
else
{
cout << "The list contains: " << endl;
while (current != NULL)
{
cout << current->theType << " ";
cout << current->name << " ";
cout << current->amount << " ";
cout << current->cleared << endl;
current = current->next;
}
}
}
答案 0 :(得分:0)
您应该使用来自C ++ STL库的std :: list作为您的程序。您可以使用push_back()函数插入到std :: list对象中。
将节点存储在std :: list中后,可以使用基于迭代器的循环来读取和显示元素。你必须超载&gt;&gt;和&lt;&lt;在这种情况下,您的结构budgetItem的运算符。
答案 1 :(得分:0)
虽然我不同意这段代码的大部分内容,但是链接列表的连接问题如下:
last = temp;
temp->next = NULL;
if (counter == 0)
{
//head = temp;
head = temp;
}
你放弃了之前指向的last
,因此没有建立链接。我想,随之而来的内存泄漏是一个额外的功能。
这样做:
temp->next = NULL;
if (last != NULL)
last->next = temp;
else
head = temp;
last = temp;
从正确确定何时停止阅读开始,您的代码可以清理。模块化budgetItem
因此明智地从std::istream
读取本身也是一个很好的步骤。
最后,我认为这是针对学术界的,否则我会告诉你不要重新发明轮子并首先使用std::vector<budgetItem>
。