我正在编写一个从链接列表中打印出项目的函数。它打印出来的东西很好,但是一旦它到达终点并碰到一个我认为为空或没有初始数字的节点,它就会打印出一个随机数(我猜是存储在计算机中)。我怎样才能解决这个问题?
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;
}
}