实现链表C



我正在做一个赋值,我想我应该使用一个链表来存储一些数据。问题是该列表没有保留所有节点。

当添加完并尝试查看节点时,它只显示添加到列表中的最后一个节点。

我将在下面写下相关部分,我希望有人能指出问题所在

我还应该指出,我测试了,在添加数据时打印数据,这确实表明它们被正确添加到了列表中)。

/**
 * 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;
}

MAIN程序:

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)。

由于这个错误,添加的第一个元素是可以的,但当您尝试添加第二个元素时,您只分配了它的空间,然后覆盖了第一个元素。

在代码的这一部分中,您需要设置变量对于当前->下一个

  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;

相关内容

  • 没有找到相关文章

最新更新