C++ 打印列表元素问题

C++ 打印列表元素问题,c++,C++,我正在编写一个从链表中打印项目的函数。它可以很好地打印出来,但是一旦它到达末尾,并且碰到一个我认为是空的或者没有初始数字的节点,它就会打印出一个随机数(我猜是存储在计算机中的)。我怎样才能解决这个问题 void printList(intNode*& intList) { intNode* current; if (intList==NULL) { cout << "No elements to print-list is empty." << endl

我正在编写一个从链表中打印项目的函数。它可以很好地打印出来,但是一旦它到达末尾,并且碰到一个我认为是空的或者没有初始数字的节点,它就会打印出一个随机数(我猜是存储在计算机中的)。我怎样才能解决这个问题

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打印列表(intNode*&intList)
{
intNode*电流;
if(intList==NULL)
{

cout如果你不初始化你的Int,当你访问它们时,你无法确定它们将返回什么。我建议初始化你所有的Int,如果仍然发生,按照Karthik的评论进行操作,并检查列表是如何初始化的。

你的操作顺序错误。你在
lastInt->nextNode中创建新节点e> 但随后将该值分配给
lastInt->intValue
。这意味着您将始终在列表末尾有一个尚未初始化的节点

整个事情看起来很复杂。这个怎么样:

intNode * intList = NULL;
intNode * lastInt = NULL;

while( intInputFile>>fileInt )
{
    // Initialise a new node.
    intNode *newNode = new intNode;
    newNode->nextNode = NULL;
    newNode->intValue = fileInt;

    // Append to list.
    if( intList == NULL ) {
        intList = newNode;
    } else {
        lastInt->nextNode = newNode;
    }
    lastInt = newNode;

    // Make noise...        
    cout << newNode->intValue <<endl;
}
intNode*intList=NULL;
intNode*lastInt=NULL;
while(intInputFile>>fileInt)
{
//初始化一个新节点。
intNode*newNode=新intNode;
newNode->nextNode=NULL;
newNode->intValue=fileInt;
//附加到列表中。
if(intList==NULL){
intList=newNode;
}否则{
lastInt->nextNode=newNode;
}
lastInt=newNode;
//制造噪音。。。

cout intValue这段代码乍一看很好,可能是你设置列表的地方出了问题,upc++没有初始化,所以如果你不设置值,它将是随机的。列表遍历看起来很好。你应该向我们展示填充列表的代码。@paddy我已经将它添加到我的原始帖子中。@AA intNode是如何定义的?ints是指整数吗?是的s、 如中所示,无论您使用何种数据结构来保存链接列表中的数字。无论它们是什么,都应该对它们进行初始化。
intNode * intList = NULL;
intNode * lastInt = NULL;

while( intInputFile>>fileInt )
{
    // Initialise a new node.
    intNode *newNode = new intNode;
    newNode->nextNode = NULL;
    newNode->intValue = fileInt;

    // Append to list.
    if( intList == NULL ) {
        intList = newNode;
    } else {
        lastInt->nextNode = newNode;
    }
    lastInt = newNode;

    // Make noise...        
    cout << newNode->intValue <<endl;
}