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

问题描述 投票:1回答:1

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

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

c struct
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.