2012-12-20 117 views
0

我正在写一个函数,用于打印出链接列表中的项目。它正在打印出好的东西,但一旦达到最后并击中了一个我认为是空或没有初始数字的节点,它就会打印出一个随机数(我猜存储在计算机中)。我怎样才能解决这个问题?打印列表元素问题

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

这段代码看起来很好看,也许错误是你设置列表的地方 –

+1

C++不初始化,所以如果你没有设置它的值是随机的。 – rerun

+0

列表行走看起来很好。您应该向我们展示填充列表的代码。 – paddy

回答

0

如果你不初始化你的整数,当您访问他们,你不能确定的,他们将返回的内容。我建议初始化您的所有整数,如果它仍然存在,请按照Karthik的评论和检查您的列表如何初始化。

+0

通过整数,你的意思是整数吗? –

+0

是的。就像在任何数据结构中,你用来在链表中保存数字。不管他们是什么,他们都应该被初始化。 – Nashibukasan

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”,直到完成循环(所有中间的人是多余的),或者使用虚拟头节点的其他选项。但让我们保持简单。

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