hash表建立 很久没写数据结构了

本文介绍了一个简单的哈希表实现方法,使用C语言编写。该实现包括插入元素和输出哈希表的功能,通过取模运算确定哈希值,并处理了哈希冲突。文章提供了完整的源代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
auhtor:lx
date 4.9 2011
brief hash table
*/

#include
<stdio.h>
#include
<stdlib.h>
#include
<stdbool.h>
#define hash_num 5

typedef
char Bool;

struct hash_node
{
int date; /*结点值*/
struct hash_node *next; /*下一个节点*/
Bool found;
};

struct hash_node* hash_table[hash_num]; /*存储hash table 所有信息*/

void hash_table_found( int value )
{
int hash;
hash
= value % hash_num;

/* 建立结点 */
struct hash_node* node = (struct hash_node*)malloc( sizeof( struct hash_node) );
node
->date = value;
node
->next = NULL;
node
->found = 't';

if ( hash_table[ hash ]->found == 'f' )
{
hash_table[ hash ]
->date = value;
hash_table[ hash ]
->next = NULL;
hash_table[ hash ]
->found = 't';
}
else
{
node
->next = hash_table[ hash ];
hash_table[ hash ]
= node;
}

}
void hash_table_output()
{
int i = 0;

for ( ; i < hash_num; i++ )
{
if ( hash_table[i]->found == 't' )
{
while ( hash_table[i] != NULL )
{
printf(
"%d\t", hash_table[i]->date );
hash_table[i]
= hash_table[i]->next;
}

printf(
"\n" );
}
}
}

int main( void )
{
/*要放入hash表的数据*/
int a[10] = { 0, 0, 400, 20, 12, 450, 2222, 30, 1 , 200 };

int j;
for ( j = 0; j < hash_num; j++ )
{
hash_table[j]
= ( struct hash_node* )malloc( sizeof( struct hash_node ) );
hash_table[j]
->date = 0;
hash_table[j]
->next = NULL;
hash_table[j]
->found = 'f';

}

int i = 0;
for ( ; i < 10; i++ )
{
hash_table_found( a[i] );
}

hash_table_output();
}

转载于:https://www.cnblogs.com/lxgeek/archive/2011/04/09/2010573.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值