首页 > 解决方案 > 有两个哈希表,当删除一个项目时,它会删除另一个

问题描述

我实现了一个哈希表,并像这样初始化了两个不同的哈希表:

hashtable *active_users = create();
hashtable *inactive_users = create();

上面哈希表的一个元素如下所示:

typedef struct user{
    char nick[6];
    char name[26];
    int n_messages;
    bool occupied;
}user;

在我的主程序中,我有一个函数可以删除用户active_users并将其插入其中inactive_users,问题是当从 中删除项目active_users后,将其插入其中后inactive_users,出于某种原因将其删除。

hashtable * delete_user(hashtable *active_users, hashtable *inactive_users, char *input_a){
    if(contains(active_users, input_a) != -1){
        user *tmp = get_item(active_users, input_a); //gets the user from the active_users hashtable
        if(load_factor(inactive_users)) //checks the hashtable size
            inactive_users = resize_HashTable(inactive_users); // if needed it resizes
        insert2(inactive_users, tmp); //insert in inactive_users
        print_table(inactive_users);
        printf("\n");
        delete_item(active_users, input_a); //deletes from active_users
        print_table(inactive_users);
        printf("+ user %s removed\n", input_a);
    }else{
        printf("+ user %s doesnt exist\n", input_a);
    }
    return inactive_users;
}

inactive_users在上面的代码中,我在插入新用户并从其中删除同一用户后打印了哈希表,active_users以便您可以看到问题。

inactive_users插入后:

i: 0, nick: me, name: mig
i: 1, nick: -, name: -
i: 2, nick: -, name: -
i: 3, nick: -, name: -
i: 4, nick: -, name: -

inactive_users从删除后active_users

i: 0, nick: -, name: -
i: 1, nick: -, name: -
i: 2, nick: -, name: -
i: 3, nick: -, name: -
i: 4, nick: -, name: -

要从哈希表中删除一个项目,我只需将其变量“占用”标记为 false,这意味着该点现在可以自由用于插入。编码:

void delete_item(hashtable *HashTable, char *nick){
    int position = contains(HashTable, nick);
    if(position != -1){
        HashTable[position].buckets->occupied = false;
        HashTable->elements--;
    }
}

标签: chashtable

解决方案


occupied是结构的一个字段,您在..user上设置为 falsedelete_item

相反,您应该将存储桶设置为 null

void delete_item(hashtable *HashTable, char *nick){
    int position = contains(HashTable, nick);
    if(position != -1){
        HashTable[position].buckets = null;
        HashTable->elements--;
    }
}

推荐阅读