2015-12-22 73 views
2
struct List 
{ 
    Post *p; //a random class 
    List *next;  
}; 

,我用它来插入数据C++链接列表:变量问题

List *help; 
help=(*leaf)->start; //leaf is a node where is the start of the list 
while(help!=NULL) 
    help=help->next; 
help=new List; 
help->p=new Post() 
help->next=NULL 

为什么不工作?

对不起我的英文不好,如果这是太容易了..再次感谢

回答

1

问题1:

在while循环你重复而helpNULL,所以你离开while循环时helpNULL。你想保留列表中的最后一个节点。最后一个节点是help->next == NULL。所以,你的while循环应该是这样的:

while (help->next != NULL) 
    help = help->next; 

问题2:

当您设置help = new List();你在你的名单失去了参考的最后一个节点。 help现在包含新的List实例,但不能将其设置为链表中最后一个元素(您在while循环中搜索的元素)的next条目。

所以,你可以继续:

help->next = new List(); // allocate node and set it as next 
help = help->next;  // now you can set help to the new node 
help->p = new Post(); 
help->next = NULL; 

注意:您应该用大括号写while循环 - 否则,你可能会感到困惑,这部分代码是循环的一部分,这是不。最终这是个人风格,但我建议它初学者:

while (help->next != NULL) { 
    help = help->next; 
}