我正在写一个函数,用于打印出链接列表中的项目。它正在打印出好的东西,但一旦达到最后并击中了一个我认为是空或没有初始数字的节点,它就会打印出一个随机数(我猜存储在计算机中)。我怎样才能解决这个问题?打印列表元素问题
void printList(intNode*& intList)
{
intNode* current;
if (intList==NULL)
{
cout << "No elements to print-list is empty." << endl;
}
else
{
cout << "Elements in list:" << endl;
current = intList;
while (current!=NULL)
{
cout << current->intValue <<endl;
current=current->nextNode;
}
if (current==NULL)
{
cout << "End of list" << endl;
}
}
}
这里就是我创建列表:
void createList(intNode*& intList)
{
intNode* lastInt; //points to last integer in file
lastInt = NULL;
int fileInt; //int read from input file
ifstream intInputFile;
intNode* anotherInt;
anotherInt = new intNode;
intInputFile.open("intInput.txt");
if (intInputFile.is_open())
{
cout << "intInput.txt open successful" << endl;
cout << "check" <<endl;
while(intInputFile>>fileInt)
{
if(intList==NULL)
{
intList = anotherInt;
lastInt = anotherInt;
lastInt->nextNode = NULL;
lastInt->nextNode = new intNode;
}
else
{
lastInt = lastInt->nextNode;
lastInt->nextNode = NULL;
lastInt->nextNode = new intNode;
}
lastInt->intValue = fileInt;
cout << lastInt->intValue <<endl;
}
lastInt->nextNode->nextNode=NULL;
intInputFile.close();
cout << "List created from input file" << endl;
}
else
{
cout << "intInput.txt open unsuccessful" << endl;
}
}
这段代码看起来很好看,也许错误是你设置列表的地方 –
C++不初始化,所以如果你没有设置它的值是随机的。 – rerun
列表行走看起来很好。您应该向我们展示填充列表的代码。 – paddy