簡體   English   中英

鏈表的一部分未打印

[英]part of linked list not printing

因此,我正在處理鏈表代碼,我有兩個功能:一個向前構建列表,另一個向后構建列表。 我的代碼運行了,但是我遇到的問題是,它只打印出了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;
    }
}

該程序首先執行buildlistForward()因此,在讀取文件末尾時,對於buildlistBackward()沒有任何內容可讀取,您需要通過打開ifstream從文件中再次讀取,但是您也可以向后打印鏈接列表通過實現尾部,訪問最后一個node並從最后到第一打印每個node ,而不是在輸入每個節點時讀取輸入和打印。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM