打印出列表元素问题

时间:2012-12-20 02:16:41

标签: c++

我正在编写一个打印出链接列表中的项目的函数。它打印出来的东西很好,但是一旦它到达终点并命中一个我认为是null或没有初始数字的节点,它会打印出一个随机数(我猜是存储在计算机中)。我该如何解决这个问题?

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;
}
}

2 个答案:

答案 0 :(得分:0)

如果您没有初始化您的整体,当您访问它们时,您无法确定它们将返回什么。我建议初始化你的所有整数,如果它仍在发生,请按照Karthik的评论并检查你的列表是如何初始化的。

答案 1 :(得分:0)

你正在以错误的顺序做事。您可以在lastInt->nextNode中创建新节点,然后将值分配给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;
}

还有其他填充列表的选项,包括在完成循环之前不设置“NULL”(所有中间的都是冗余的),或者使用虚拟头节点。但是,让我们保持简单。

请注意,我在循环中使用了一个临时变量,以便非常清楚我为哪个节点分配数据。