hash表原理

哈希表原理与实现

哈希表又称散列表,通过键来访问值的数据结构。哈希表内部用数组存储value, 首先通过映射函数(哈希函数)将key映射成size_t型的下标并对数组长度取余, 然后访问数组。

由于哈希函数原因,不同key会被映射成相同的下标。这是可以通过拉链法,用链表数组存储value。相同映射为相同下表的键值对会被存储在一个链表中,链表每个节点都有key,value字段。

#include <iostream>
#include <string>
#include <stack>
#include 
哈希是一种基于哈希算法实现的高效数据结构,用于存储键值对(key-value pairs)。其核心原理是借助哈希函数将键(key)映射到数组的某个位置(索引),进而在该位置存储对应的值(value)。在理想状况下,查找、插入和删除操作的时间复杂度能接近 O(1) [^1]。 哈希的“哈希”即指哈希函数(Hash Function),它是哈希的核心,负责把输入(键)映射到中的某个位置(桶)。哈希函数的设计对哈希的性能和冲突处理起着关键作用。而“”指的是用于存储数据的数组,哈希通过哈希函数把键映射到这个数组的索引位置,以此高效地进行查找、插入和删除操作 [^2]。 不过,哈希冲突可能会出现,当哈希冲突发生且哈希的负载因子过高(即存储元素数量接近哈希容量)时,查找、插入和删除操作的时间复杂度可能会退化为 O(n),比如所有元素都存储在同一个链中。所以,哈希通常会在负载因子达到一定阈值时进行扩容,以维持良好的性能 [^2]。 以下是一个简单的 C 语言实现的哈希示例(采用链地址法处理哈希冲突): ```c #include <stdio.h> #include <stdlib.h> // 定义哈希节点 typedef struct HashNode { int key; int value; struct HashNode *next; } HashNode; // 定义哈希 typedef struct HashTable { HashNode **buckets; // 桶数组 int size; // 总容量 int count; // 当前元素数 } HashTable; // 创建哈希 HashTable* createHashTable(int size) { HashTable *table = (HashTable*)malloc(sizeof(HashTable)); table->size = size; table->count = 0; table->buckets = (HashNode**)calloc(size, sizeof(HashNode*)); return table; } // 简单的哈希函数 int hashFunction(int key, int size) { return key % size; } // 插入键值对 void insert(HashTable *table, int key, int value) { int index = hashFunction(key, table->size); HashNode *newNode = (HashNode*)malloc(sizeof(HashNode)); newNode->key = key; newNode->value = value; newNode->next = table->buckets[index]; table->buckets[index] = newNode; table->count++; } // 查找键对应的值 int search(HashTable *table, int key) { int index = hashFunction(key, table->size); HashNode *current = table->buckets[index]; while (current != NULL) { if (current->key == key) { return current->value; } current = current->next; } return -1; // 未找到 } // 释放哈希内存 void freeHashTable(HashTable *table) { for (int i = 0; i < table->size; i++) { HashNode *current = table->buckets[i]; while (current != NULL) { HashNode *temp = current; current = current->next; free(temp); } } free(table->buckets); free(table); } int main() { HashTable *table = createHashTable(10); insert(table, 1, 100); insert(table, 11, 200); printf("Key 1 value: %d\n", search(table, 1)); printf("Key 11 value: %d\n", search(table, 11)); freeHashTable(table); return 0; } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值