2014-10-02 98 views
-1

你好,我是一名思考鏈表的初學C++程序員。我想出了下面的代碼,但是當我運行它時,我的電腦崩潰了。我想知道是什麼導致我的電腦做到這一點。爲什麼我的電腦在我建立鏈表時崩潰?

#include <iostream> 
using namespace std; 
struct list 
{ 
    int value; 
    list* nextlist; 
}; 
list* getnewstruct (list* phead, int nextvalue); 
void printarray (list* phead); 
int main() 
{ 
    int nextvalue = 0; 
    list* phead = NULL; 
    while (nextvalue < 5) { 
     phead = getnewstruct (phead, nextvalue); 
    } 
    printarray (phead); 
} 
list* getnewstruct (list* phead, int nextvalue) 
{ 
    list* newlist = new list; 
    newlist->value = nextvalue; 
    newlist->nextlist = phead; 
    return newlist; 
} 
void printarray (list* phead) 
{ 
    while (phead->nextlist != NULL) { 
     cout<<phead->value<<endl; 
     printarray (phead->nextlist); 
    } 
} 
+0

in main,nextvalue永遠不會更新。 – Max 2014-10-02 14:36:08

+6

您需要在具有獨立進程的操作系統上解決這個問題,以免它使整個計算機崩潰。 – 2014-10-02 14:37:36

+0

nextvalue始終爲0,所以始終爲<5,所以它會循環直到內存不足,然後bad_alloc但可能會凍結您的計算機,因爲它在過渡期內的內存不足 – CashCow 2014-10-02 14:39:06

回答

1

你的程序只是簡單地運行「永遠」,因爲你不是遞增nextvalue導致的while (nextvalue < 5)在每次迭代運行。