2014-11-19 2 views
0

Это реализация хэш-таблицы.Вставка и удаление из связанного списка

У меня есть функция вставки, но как вернуть связанный список?

Я знаю, что удаление еще не сделано, но я понимаю концепцию, моя проблема возвращает скорректированный список.

Я попытался сделать хэш-таблицу глобальной переменной, но программирование заставило бы ее запустить.

#include <stdio.h> 
#include <stdlib.h> 
#include <ctype.h> 
#include <assert.h> 
#include <string.h> 

struct node { 
    char * data; 
    struct node * next; 
}; 

struct hashtable { 
    struct node ** table; 
    int size; 
    int nentries; 
}; 

struct hashtable * hashtable_new(int size) { 
    struct hashtable * result; 
    result = malloc(sizeof(struct hashtable)); 
    result -> size = size; 
    result -> nentries = 0; 
    result -> table = malloc(sizeof(struct node) * size); 
    int i = 0; 

    for (i = 0; i < result->size; i++) { 
     result->table[i] = NULL; 
     // result->table[i]->data = NULL; 
    } 

    return result; 
} 

unsigned hash_string(struct hashtable *this, char * str) { 
    unsigned hash = 0; 
    int i = 0; 
    for (i = 0; str[i] != '\0'; i++) { 
     hash = hash * 37 + str[i]; 
    } 
    //return hash; 
    return hash % this-> size; 
} 

void hashtable_free(struct hashtable * this) { 
    int i; 
    struct node *table_nodes, *current, *next; 

    for(i = 0; i<this->size; i++) { 
     table_nodes = this->table[i]; 
     current = table_nodes; 

     while (current != NULL){ 
      next = current->next; 
      free(current); 
      current = next; 
     } 
     this->table[i] = NULL; 
    } 

    free(&this->table); 
    free(&this->size); 
    free(&this->nentries); 
    free(this); 
} 

void hashtable_insert(struct hashtable * table, char * string) { 
    struct node * new_node; 
    unsigned index = hash_string(table, string); 

    if(table->table[index] == NULL) { 
     printf("\nIndex: %d", index); 
     new_node = malloc(sizeof(struct node)); 
     new_node -> next = table->table[index]; 
     new_node -> data = string; 
     printf("\nData: %s", new_node->data); 
     table -> table[index] = new_node; 
     table -> nentries++; 
     printf("\n"); 
    } else { 
     new_node = malloc(sizeof(struct node)); 
     new_node->data = string; 
     new_node->next = NULL; 
     struct node * current = table->table[index]; 
     struct node * next; 
     int size = 1; 

     while (current != NULL) { 
      next = current->next; 
      //if(current->data == string){ 
       //return; 
      //} 
      if(current-> next == NULL){ 

       //last element in list 
       current->next = new_node; 
       table->nentries++; 
       size++; 
       printf("\nIndex: %d", index); 
       printf("\nSize: %d", size); 
       printf("\nData: %s", current->next->data); 
       printf("\n"); 
       return; 
      } 
      current = next; 
      size++; 
     } 
    } 
} 

void remove_hash(struct hashtable * this, char * item) { 
    //unsigned index = hash_string(this, item); 
} 

int lookup(struct hashtable * this, char * item) { 
    struct node *temp; 
    unsigned int index = hash_string(this, item); 

    temp = this->table[index]; 
    while(temp != NULL) { 
     // do something 
     printf("%s, ", temp->data); 

     if(temp->data == item) { 
      printf("found %s\n", temp->data); 
     } 
     temp = temp->next; 
    } 
    return 0; 
} 

void print(struct hashtable * this) { 
    int i = 0; 
    printf("\n Size %d \n", this->size); 
    if(this == NULL) { 
     printf("Please construct the hashtable"); 
     return; 
    } 

    for (i = 0; i < this->size; i++) { 
     if(this->table[i] == NULL) { 
      printf("\n %d: <empty>", i); 
     } else { 
      printf("\n %d: %s ", i, this->table[i]->data); 
      if(this->table[i]->next != NULL) { 
       printf("%s ", this->table[i]->next->data); 
      } 
     } 
    } 
} 

int main(int argc, char **argv) { 
    //struct node *theNode; 
    struct hashtable *theHash; 

    theHash = hashtable_new(9); 

    hashtable_insert(theHash, "I"); 
    hashtable_insert(theHash, "am"); 
    hashtable_insert(theHash, "a");; 
    hashtable_insert(theHash, "fish"); 
    hashtable_insert(theHash, "glub"); 
    print(theHash); 

    hashtable_insert(theHash, "glub"); 
    lookup(theHash, "I"); 

    print(theHash); 

    //printf("\n\n\n"); 
    hashtable_free(theHash); 
    //print(theHash); 

    return 0; 
} 
+0

Вы рассортируете неправильный объем памяти для своего стола (слишком много). Эта строка 'result -> table = malloc (sizeof (struct node) * size);' должен иметь 'sizeof (struct node *)' вместо 'sizeof (struct node)'. Также, каков ваш вопрос? Вы спрашиваете о 'lookup' или' hashtable_insert'? – JS1

ответ

0

Поскольку C не позволит вам пройти по ссылке, вы можете попробовать возвращение Хеш затем переназначить переменную с результатом hashtable_insert:

struct hashtable *hashtable_insert(struct hashtable *table, char *string) { 
    // awesome code here 
    return current; 
} 

, а затем вызвать его:

theHash = hashtable_insert(theHash, "Wow!"); 
+0

Я получаю тот же результат, потому что 'current' - это другой связанный список. Я должен сохранить заголовок 'current' и вернуться к нему после вставки и заменить' table-> table [index] '. –

+0

Вместо этого попробуйте вернуть 'current'. Обновленный мой ответ, чтобы отразить это. – APerson

+0

Это вернет 'Node' не связанный список или хеш-таблицу. –

Смежные вопросы