您的位置:首页 > 编程语言 > C语言/C++

C/C++ 实现哈希表(hash table)

2017-10-18 12:29 375 查看
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#define MAX_HASH_TABLE_LEN 10
using namespace std;

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)
{
if (NULL == hashtable_index)
return;

for (int 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()
{
HASH_TABLE* h = create_hash_table();

for (int 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);
cout << endl;
system("pause");
return 0;
}




运行结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息