[英]C LinkedList adding node to end
我正在嘗試創建一個可以向鏈接列表添加信息的程序。 看來,一旦我添加了兩個以上的節點,以前添加的節點就會被覆蓋。 進行這項工作時我缺少什么嗎?
我從此函數開始,該函數要么添加到列表的前面,要么如果已經有一個節點添加到列表的前面,則調用函數addToBack
ListHeadPtr Front(ListHeadPtr theList, list * toBeAdded){
printf("Received in addToFront\n");
if(theList == NULL){
theList = toBeAdded;
return(theList);
}
else{
theList = addToBack(theList,toBeAdded);
/*toBeAdded->next = theList;
theList = toBeAdded;*/
return (theList);
}
}
ListHeadPtr back(ListHeadPtr theList, item * toBeAdded){
if(theList == NULL){
theList = addToFront(theList,toBeAdded);
return(theList);
}
else{
list *current;
current = theList;
while (current->next!=NULL){
current = current->next;
}
current->next = toBeAdded;
return(current);
}
}
item(toBeAdded由此函數定義
item *createItem(int time){
item *itemPtr = (list *) malloc(sizeof(item));
if(NULL == itemPtr)
{
printf("Unable to create item\n");
return (NULL);
}
itemPtr->waitTime = time;
itemPtr->next = NULL;
return (itemPtr);
}
在您的[addTo] Back函數中
return(current);
應該返回列表的開頭。 您正在做的是將列表截斷為最后兩個元素。
避免此類錯誤的一種方法是准確掌握您的語義。 addToBack
定義要返回什么? 調用者希望它返回添加了節點的列表。 函數之前應該有文檔注釋,說明它的作用和返回的作用。 該注釋可以指導您編寫代碼...如果末尾只有一個返回列表的語句,而不是多次返回,則代碼會更好。 然后這個錯誤就不可能發生。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.