[英]Implementing a Linked List C
我正在做一個任務,我想我應該使用鏈表來存儲一些數據。 問題是列表不保留所有節點。
添加完成后我嘗試查看節點,它只顯示添加到列表的最后一個節點。
我將編寫下面的相關部分,我希望有人可以指出問題是什么。(我懷疑它必須是與malloc相關的東西。地址在函數完成其工作后被破壞,但我不確定。
另外我應該指出,我測試過,在添加數據時打印數據,它確實顯示它們被正確添加到列表中)。
/**
* Adds command name and it's hash onto the linked list
* returns 1, if successful
* returns 0, if failed
*/
int addToList(struct CMDList *head, char *pathCommand[], char *hash){
int result = 0;
/** If head was pointing to NULL, list empty, add at the beginning */
if(head->path == NULL){
head->path = pathCommand[0];
head->command = pathCommand[1];
head->hash = hash;
head->next = NULL;
result = 1;
}else{
struct CMDList *current = head;
/** Find tail of the list */
while(current->next != NULL){
current = current->next;
}
current->next = (struct CMDList *)malloc(sizeof(struct CMDList));
if(current->next != NULL){
current->path = pathCommand[0];
current->command = pathCommand[1];
current->hash = hash;
current->next = NULL;
result = 1;
}
}
return result;
}
主要計划:
int main(int argc, char *argv[]){
/** CODE DELETED */
/** initialize list for storing cmds from config file */
/** cmdList is the head node that i use to traverse the list */
cmdList = (struct CMDList *)malloc(sizeof(struct CMDList));
if(cmdList != NULL){
cmdList->path = NULL;
cmdList->command = NULL;
cmdList->hash = NULL;
cmdList->next = NULL;
}else{
printError("Silent Exit: couldn't initialize list to store commands of config file");
exit(1);
}
/** CODE DELETED **/
/** add new data to the list */
if(!addToList(cmdList,arrayCommand,sha)){
printError("Silent Exit: couldn't add to list");
exit(1);
}
}
在這部分代碼中:
if(current->next != NULL){
current->path = pathCommand[0];
current->command = pathCommand[1];
current->hash = hash;
current->next = NULL;
result = 1;
}
你必須使用current->next->...
而不是current->...
,因為你的新元素是current->next
,而不是current
(事實上,你檢查過current->next != NULL
)。
由於此錯誤,添加的第一個元素很好,但是當您嘗試添加第二個元素時,您只需分配其空間,然后覆蓋第一個元素。
在這部分代碼中,您要為current-> next設置變量
if(current->next != NULL){
current->path = pathCommand[0];
current->command = pathCommand[1];
current->hash = hash;
current->next = NULL;
result = 1;
}
另一個選擇是,在執行malloc時,設置一個指向新結構的臨時指針,給出你需要的值,然后設置current->next = temp;
您也可以跳過while步驟。 您可以使用名為tail的指針指向列表末尾。
並做一些類似的事情
temp=malloc(...)
temp->path = ...
...
tail->next = temp;
tail = temp;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.