如何从C中的结构中删除元素?

时间:2019-12-19 00:27:26

标签: c struct

我想知道是否有一种方法可以从结构中删除键及其值。这是我的结构:

typedef struct dictionary {
    char *key;
    int num;
    struct dictionary *array;
    struct dictionary *dic;
    struct dictionary *next;
} Dictionary;

这就是我对函数所做的事情:**

int removeElement(Dictionary *dictionary, const char *key){
    if(!dictionary)
        return 0;
    char *aux=(char *)malloc(sizeof(char *));
    strcpy(aux,key);
    while (dictionary!=NULL){
        if (strcmp(dictionary->key, aux) == 0)
        {
            //here i suppose to write what to do when i find the key but i just don't know how
        }
        dictionary=dictionary->next;
    }
}

如果它能够删除一个元素,则返回1,否则返回0

1 个答案:

答案 0 :(得分:0)

您必须找到上一个字典条目,然后将其下一个指针设置为指向下一个字典条目(一个要删除的具有匹配键的字典指针。

完成此操作后,词典链接列表将是连续的,并且任何内容都不会指向您当前的条目(您要删除的条目)。

此时您可以释放当前条目,它将永远消失。

所以...现在,您必须弄清楚如何查找上一个词典条目。为此,我通常在链接列表中也使用前一个指针,但是您也可以返回到链接列表的第一个元素并向前计数,直到找到匹配项之前的元素。

如果您以前有一个指针,也可以这样:

dictionary->previous->next=dictionary->next; //<-- patch over the current entry
free(dictionary->key); //<-- not sure, but this looks like it has been malloced
free(dictionary); //<-- delete the current entry