跟踪链表



我仍然无法弄清楚如何跟踪我的链表,但已经取得了一些进展。

我的代码正在通过节点完美地读取文本文件中的数据,但我似乎无法弄清楚如何将其正确传输到 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;
    }
}
}

虽然我不同意这段代码的大部分布局方式,但连接链表的问题如下:

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>

你应该在程序中使用 std::list C++ STL 库。您可以使用 push_back() 函数插入到 std::list 对象中。

将节点存储在 std::list 中后,可以使用基于迭代器的循环来读取和显示元素。在这种情况下,您必须重载结构预算的>>和<<运算符项。

最新更新