C-哈希表键的链接列表 [英] C - Linked list of hash table keys

查看:84
本文介绍了C-哈希表键的链接列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试创建一个输入哈希表并返回键的链表的函数. 这是列表节点的结构:

I try to create a function that get in input an hash table and return a linked list of keys. This is the struct of a list node:

struct hash_table_key_list_node_s {
  char *key;
  struct hash_table_key_list_node_s* next;
};

typedef struct hash_table_key_list_node_s hash_table_key_list_node_t;
typedef hash_table_key_list_node_t* hash_table_key_list_t;

我不明白为什么列表只包含一个元素,而哈希表却包含330个元素. 这是函数的代码:

I don't understand why the list contains only one element but the hash table contains 330 element. This is the code of the function:

hash_table_key_list_t hash_table_keys(hash_table_t hash_table) {



hash_table_key_list_t list, tail, p;
  list = tail = NULL;

  if ( hash_table != NULL && hash_table->slots != NULL ) {

    size_t index = 0;
    while ( index < hash_table->capacity ) {

      hash_table_list_node_t *node = hash_table->slots[index].head;
      while ( node != NULL ) {

        p = malloc(sizeof(hash_table_key_list_node_t));
        p->key = strdup(node->key);

        if ( node != NULL ) {
          list = tail = p;
        }
        else { 
          tail->next = p;
          tail = p;
        }

        node = node->next;
      }

      index++;
    }
  }

  return list; 
}

推荐答案

列表插入逻辑中存在一个错误:

There's a bug in you list insertion logic:

if (node != NULL) {

应该是:

if (list == NULL) {

由于此时node始终不是NULL,因为这是循环的条件,因此您实际上要检查这是否是要插入到新链接列表中的第一个条目(检查list是否为NULL将实现此目的.请注意,还应先检查mallocstrdup是否成功,然后再将其添加到列表中,清理链接列表(释放列表中分配的部分)并在内存不足时返回某种错误指示.从表中创建列表.

As node is always not NULL at this point as it's the condition for you loop and you actually want to check if this is the first entry to be inserted into the new link list (checking if list is NULL will achieve this). Note you should also check if your malloc and strdup are successful before adding it to the list, cleaning up the link list (freeing allocated part of the list) and returning some kind of error indication if there isn't enough memory to create the list from the table.

这篇关于C-哈希表键的链接列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆