Я не понимаю, почему мой hashTable не работает должным образом C - PullRequest
0 голосов
/ 10 июня 2018

Я создаю HashTable в C, который использует двойной указатель Node и использует отдельную цепочку для разрешения коллизий, но когда я запускаю свой код, он не помещает коллизии в связанный список.

HTable *createTable(size_t size, int (*hashFunction)(size_t tableSize, 
int key),void (*destroyData)(void *data),void (*printData)(void 
*toBePrinted)){
HTable * h = malloc(sizeof(HTable));

h->size = size;
h->destroyData = destroyData;
h->hashFunction = hashFunction;
h->printData = printData;

h->table = malloc(h->size * sizeof(Node*));
for(int i = 0; i < h->size; i++){

    h->table[i] = malloc(sizeof(Node));
    h->table[i]->key = 0;
    h->table[i]->data = NULL;
    h->table[i]->next = NULL;
}

return h;
}

Node *createNode(int key, void *data){
Node * n = malloc(sizeof(Node));

n->key = key;
n->data = data;
n->next = NULL;

return n;
}

void insertData(HTable *hashTable, int key, void *data){
if(hashTable != NULL){
    Node * n = createNode(key, data);
    int index = hashTable->hashFunction(hashTable->size, key);

    if(hashTable->table[index] != NULL)
        if(hashTable->table[index]->key == key){
            if(hashTable->table[index]->next != NULL){
                n->next = hashTable->table[index]->next;
                hashTable->table[index] = n;
            }
            else
                hashTable->table[index] = n;
        }
        else{
            if(hashTable->table[index]->next != NULL){
                Node * itr = hashTable->table[index];
                while(itr->next != NULL){
                    itr = itr->next;
                }
                itr->next = n;
            }
            else
                hashTable->table[index] = n;
        }
    else{
        hashTable->table[index] = n;
    }
}
}

иУдары HTable и Удары Node выглядят следующим образом:

typedef struct Node
{
int key;
void *data;
struct Node *next; 
} Node;

typedef struct HTable
{
size_t size; 
Node **table;
void (*destroyData)(void *data); 
int (*hashFunction)(size_t tableSize, int key); 
void (*printData)(void *toBePrinted); 
}HTable;

Я думаю, что у меня возникла проблема в моей функции insertData, когда я использую итератор для поиска последнего элемента в связанном списке.Это или я неправильно понимаю двойной указатель на узел.

1 Ответ

0 голосов
/ 12 июня 2018

Я выяснил, почему данные не были связаны.Если ключи не совпадают, он переходит к оператору else, а первый оператор if в этом блоке спрашивает, не является ли hashTable-> table [index] -> next значением NULL, когда он должен был спрашивать, если hashTable-> table [index] был НЕДЕЙСТВИТЕЛЕН.Это связано с тем, что мог существовать один узел, а его следующий указывал бы на NULL, и тогда данные были бы переопределены.Спасибо за ответы, и я добавил комментарии, которые были отличным советом, потому что это помогло мне найти ошибку.так что спасибо @wildplasser

Вот код, если кому-то интересно:

void insertData(HTable *hashTable, int key, void *data){
if(hashTable != NULL){
    Node * n = createNode(key, data);
    int index = hashTable->hashFunction(hashTable->size, key);

    //Check if hashTable table node contains data
    if(hashTable->table[index]->data != NULL)
        //Check if the key at that index matches the incoming key
        if(hashTable->table[index]->key == key){
            //checks if there is more than one node in the chain and replaces the
            //first piece of data in the chain
            if(hashTable->table[index] != NULL){
                n->next = hashTable->table[index]->next;
                hashTable->table[index] = n;
            }
        }
        //if the keys do not match
        else{
            //check if their is one node in the chain
            if(hashTable->table[index] != NULL){
                Node * itr = hashTable->table[index];
                //iterate through the chain to last node
                while(itr->next != NULL){
                    itr = itr->next;
                }
                //insert node into end of chain
                itr->next = n;
            }
        }
    //if there is no data in the node insert the data
    else
        hashTable->table[index] = n;

}
}
...