在C中添加两次哈希表

时间:2016-05-31 16:34:30

标签: c linked-list hashtable

根据rehashing部分中的print语句,我可以看到同一个字符串被多次添加到表中。我相信问题在于这个功能,虽然我看不到哪里。返回下面的print语句永远不会执行,因此我知道该函数实际执行。

关于问题出在哪里或者我应该如何找到它的任何想法?谢谢。我们的存储库中的完整代码位于:

https://github.com/csking1/buddhism/blob/master/Finding/hash_tables.c

void add_to_table(HashTable *h, char* str, LinkedList* new){
  unsigned int hashval = hash(h, str);
  LinkedList *list;

  // walk through the table and check for the first free spot, start at hash val and go to the top
  for (int i = hashval; i<h->size; i++){
    list = h->table[i];
    if (list == NULL){
        new->next = h->table[i];
        h->table[i] = new;
        new->string = str;
        return;
        printf("%s\n", "didn't return");
    }
  }
  // start at the bottom of the table, check for the first free spot up to hash val, then return
  for (int i = 0; i < hashval; i++){
    list = h->table[i];
    if (list == NULL){
        new->next = h->table[i];
        h->table[i] = new;
        new->string = str;
        return;
    }
  }
}

对于完整视图,这是字符串查找功能。这会在add_to_table()函数之上调用一行或两行,如果字符串已经存在,则返回。

LinkedList *lookup_string(HashTable *h, char *str){
  LinkedList *list;
  unsigned int hashval = hash(h, str);

  for (int i = hashval; i < h->size; i++){
    list = h->table[i];
    if (list == NULL){
      return NULL;
    }
    if (list != NULL){
      if (strcmp(str, list->string) == 0){
        return list;
      }
    }
  }
  for (int i = 0; i < hashval; i++){
    list = h->table[i];
    if (list == NULL){
      return NULL;
    }
    if (list != NULL){
      if (strcmp(str, list->string) == 0){
        return list;
      }
    }
  }
  return NULL;
}

0 个答案:

没有答案