链接列表的一部分不打印

时间:2015-12-14 22:09:00

标签: c++

所以我正在处理链表代码,我有两个功能:一个用于构建前向列表,另一个用于向后构建列表。 我的代码运行但我遇到的问题是它只将函数打印到buildlistForward()而不是buildlistBackward()

#include <iostream>
#include <fstream>
using namespace std;

ifstream fin;
//ofstream fout;
struct nodeType
{
    int num;
    nodeType *next;
};
void buildlistForward();
void buildlistBackward();
//void deleteHead(nodeType);
int main()
{
    fin.open("testscores_input.txt");
    buildlistForward();
    buildlistBackward();

    return 0;
}
void buildlistForward()
{
    nodeType *head = NULL, *trail = NULL, *current = NULL;
    int digit;
    cout << "The list built forward is: " << endl;
    while (fin >> digit)
    {
        if (head == NULL)
        {
            head = new nodeType;
            head->num = digit;
            head->next = NULL;
            trail = head;
        }
        else
        {
            current = new nodeType;
            current->num = digit;
            current->next = NULL;
            trail->next = current;
            trail = current;
        }
    }
    current = head;
    while (current != NULL)
    {
        cout << current->num << endl;
        current = current->next;
    }
}
void buildlistBackward()
{
    nodeType *head1 = NULL, *current1;
    int digit;
    cout << "The list built backward is: " << endl;
    while (fin >> digit)
    {
        if (head1 == NULL)
        {
            head1 = new nodeType;
            head1->num = digit;
            head1->next = NULL;
        }
        else
        {
            current1 = new nodeType;
            current1->num = digit;
            current1->next = NULL;
            current1->next = head1;
            head1 = current1;
        }
    }
    current1 = head1;
    while (current1 != NULL)
    {
        cout << current1->num << endl;
        current1 = current1->next;
    }
}

1 个答案:

答案 0 :(得分:0)

程序首先执行buildlistForward()所以当读取文件末尾时,没有什么可以读入buildlistBackward(),你需要通过打开ifstream再次从文件读取,但是你可以还可以通过实现尾部向后打印链表,并访问最后一个node并从最后一个到第一个打印,而不是在输入每个节点时读取输入和打印。

相关问题