为什么当我制作一个链表时,我的电脑会崩溃

Why does my computer crash when I make a linked list?

本文关键字:链表 我的 电脑 崩溃 一个 为什么      更新时间:2023-10-16

大家好,我是一名初级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);
    }
}

您的程序只是"永远"运行,因为您没有递增nextvalue,这会导致while (nextvalue < 5)在每次迭代中运行。