2015-12-22 71 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; 
}