gpt4 book ai didi

c - 如何用 C 语言打印哈希表?

转载 作者:行者123 更新时间:2023-11-30 18:54:36 25 4
gpt4 key购买 nike

我有一个 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 );
}

最佳答案

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

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;
}

关于c - 如何用 C 语言打印哈希表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30067048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com