2015-12-14 98 views
0

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

一旦'buildlistForward()'完成,你已經到達文件的末尾,沒有更多的數據可供讀取。 –

+0

您將*打印*與*修改*數據結構交錯。這或多或少地要求麻煩。請重新編寫代碼:引入一個'print'方法或其他等價物。分開負責。 –

+0

你確定'buildlistForward()'完成了嗎? –

回答

0

程序沒有buildlistForward()第一所以當文件末尾讀有什麼好讀進入buildlistBackward(),您需要通過打開ifstream再次從文件中讀取數據,但是您也可以通過實施尾部向後打印鏈接列表,並訪問最後一個node,並從最後一個打印到第一個,而不是讀取輸入並在每個節點輸入時進行打印。