#include<stdio.h>
#include<string.h>
#define MAX_HASH_TABLE_LEN 10
#define true 1
#define false 0
typedef int bool;
typedef struct _NODE
{
int data;
struct _NODE* next;
}NODE;
typedef struct _HASH_TABLE
{
NODE* value[MAX_HASH_TABLE_LEN];
}HASH_TABLE;
/*哈希表索引 _创建hash表()*/
HASH_TABLE* create_hash_table()
{
return (HASH_TABLE*)calloc(1, sizeof(HASH_TABLE));
}
/*数据所在的节点 _hash表当中寻找数据(哈希表索引,目标数据)*/
NODE* find_data_in_hash(HASH_TABLE* hashtable_index, int data)
{
if (NULL == hashtable_index)
return NULL;
NODE* node_index = NULL;
if (NULL == (node_index = hashtable_index->value[data % MAX_HASH_TABLE_LEN]))
return NULL;
while (node_index) {
if (data == node_index->data)
return node_index;
node_index = node_index->next;
}
return NULL;
}
/*成败 _在hash表当中插入数据(哈希表索引,目标数据)*/
bool insert_data_into_hash(HASH_TABLE* hashtable_index, int data)
{
if (NULL == hashtable_index)
return false;
NODE* node_index = NULL;
if (NULL == hashtable_index->value[data % MAX_HASH_TABLE_LEN]) /*主键table位为空*/
{
node_index = (NODE*)calloc(1, sizeof(NODE));
node_index->data = data;
hashtable_index->value[data % MAX_HASH_TABLE_LEN] = node_index;
return true;
}
if (find_data_in_hash(hashtable_index, data))/*有相同的data则不插入*/
return false;
node_index = hashtable_index->value[data % MAX_HASH_TABLE_LEN];
while (node_index->next)
node_index = node_index->next;
node_index->next = (NODE*)calloc(1, sizeof(NODE));
node_index->next->data = data;
return true;
}
/*成败 _从hash表中删除数据(哈希表索引,目标数据)*/
bool delete_data_from_hash(HASH_TABLE* hashtable_index, int data)
{
NODE* node_index = NULL;
if (NULL == hashtable_index || NULL == hashtable_index->value[data % MAX_HASH_TABLE_LEN])
return false;
if (NULL == (node_index = find_data_in_hash(hashtable_index, data)))
return false;
if (node_index == hashtable_index->value[data % MAX_HASH_TABLE_LEN]) {
hashtable_index->value[data % MAX_HASH_TABLE_LEN] = node_index->next;
goto final;
}
NODE* first_node_index = hashtable_index->value[data % MAX_HASH_TABLE_LEN];
while (node_index != first_node_index->next)
first_node_index = first_node_index->next;
first_node_index->next = node_index->next;
final:
free(node_index);
return true;
}
/*遍历打印哈希表(哈希表索引)*/
void print_hash(HASH_TABLE* hashtable_index)
{
int i = 0;
if (NULL == hashtable_index)
return;
for (i = 0; i < MAX_HASH_TABLE_LEN; ++i)
{
NODE* tmp = hashtable_index->value[i];
while (tmp)
{
printf("%d-", tmp->data);
tmp = tmp->next;
}
printf("\n");
}
}
int main()
{
int i = 0;
HASH_TABLE* h = create_hash_table();
for (i = 0; i < 100; ++i)
{
insert_data_into_hash(h, i);
}
printf("打印哈希表:\n");
print_hash(h);
printf("查找哈希表中data=10元素 : \n");
printf("%d\n", (find_data_in_hash(h, 10))->data);
printf("删除data=99元素:\n");
delete_data_from_hash(h, 99);
printf("打印哈希表:\n");
print_hash(h);
system("pause");
return 0;
}
C/C++ 实现哈希表(hash table)
最新推荐文章于 2024-07-13 19:30:43 发布