【问题标题】:How do I Print a Hash Table in C?如何在 C 中打印哈希表?
【发布时间】:2015-07-16 00:25:53
【问题描述】:

我有一个用 C 语言创建哈希表的程序。我想知道它是什么,但我不确定如何打印或显示它。我已经粘贴了下面的程序。我对哈希表比较陌生,因此我们将不胜感激!

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

#define TABLE_SIZE  7
#define NUM_INPUTS  7

int hash( char *s )
        /* Note, this is a horrible hash function.  It's here for
                instructional purposes */
{
        return strlen( s ) % TABLE_SIZE ;
}

typedef struct entry
{
        char *key;
        int     val;
        struct entry *next;
} entry;

entry* table[ TABLE_SIZE ] = { NULL };

void insert( char *s, int v )
        /* this insert is NOT checking for duplicates.  :/ */
{
        int h = hash( s );
        entry *t = (entry*) malloc( sizeof( entry ));

        t->key = s;
        t->val = v;
        t->next = table[h];
        table[h] = t;
}

void clean_table()
{
        entry *p, *q;
        int i;

        for( i=0; i<TABLE_SIZE; ++i )
        {
                for( p=table[i]; p!=NULL; p=q )
                {
                        q = p->next;
                        free( p );
                }
        }       // for each entry
}       // clean_table

int main()
{
        char* keyList[] = { "Jaga", "Jesse", "Cos", "Kate", "Nash", "Vera",
                "Bob" };

        int valList[] = { 24, 78, 86, 28, 11, 99, 38 };

        int i;

        for( i=0; i<NUM_INPUTS; ++i )
                insert( keyList[i], valList[i] );

        /* what does the table look like here? */

        clean_table();

        return( 0 );
}   

【问题讨论】:

  • 1.循环遍历范围内的table 数组,[0, TABLE_SIZE) 和 2. 对于每个条目:遍历单链表和 3.printf。如果您难以理解,请告诉我们在哪一部分。
  • 单链表遍历会是什么样子?
  • 我会以答案形式告诉你,因为那里更容易一些。
  • 编译时包含所有警告和调试信息 (gcc -Wall -Wextra -g)。然后使用调试器 (gdb)。这有助于了解程序的工作原理。
  • 请不要在您得到答案后销毁您的问题。

标签: c hashtable stdout


【解决方案1】:

根据 cmets 的要求,所需的搜索功能如下所示:

int search(const char* key, int* out_val)
{
    // Find the hash index into the table.
    const int index = hash(key);

    // Now do a linear search through the linked list.
    for (struct entry* node = table[index]; node; node = node->next)
    {
         // If we find a node with a matching key:
         if (strcmp(node->key, key) == 0)
         {
              // Output the value and return 1 for success.
              *out_val = node->val;
              return 1;
         }
    }
    // We didn't find anything. Return 0 for failure.
    return 0;
}

【讨论】:

    【解决方案2】:

    这是一个简单的 C 哈希表示例。它实际上并没有做任何错误处理,所以这根本不适合生产,但它应该有助于查看 example of a working implementation。 Here 是另一篇文章,帮助某人完成 C 中的哈希表实现。

    【讨论】:

      猜你喜欢
      • 2016-11-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-23
      • 2022-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多