📅  最后修改于: 2023-12-03 15:27:12.390000             🧑  作者: Mango
链式哈希是一种键值对存储的数据结构,它使用哈希函数将键映射到桶中,并使用链表来解决哈希冲突。链式哈希可以在插入和查找操作中实现常数时间的平均复杂度,并且很容易动态调整桶的数量。
struct ListNode {
string key;
int val;
ListNode* next;
ListNode(string k, int v) : key(k), val(v), next(NULL) {}
};
class HashTable {
private:
int size;
vector<ListNode*> table;
// 哈希函数
int hashFunc(string key) {
int hashValue = 0;
for (char c : key) {
hashValue = hashValue * 31 + int(c);
}
return hashValue % size;
}
public:
// 构造函数
HashTable(int s) : size(s), table(size, NULL) {}
// 插入操作
void put(string key, int val) {
int index = hashFunc(key);
ListNode* node = table[index];
while (node) {
if (node->key == key) {
node->val = val;
return;
}
node = node->next;
}
ListNode* newNode = new ListNode(key, val);
newNode->next = table[index];
table[index] = newNode;
}
// 查找操作
int get(string key) {
int index = hashFunc(key);
ListNode* node = table[index];
while (node) {
if (node->key == key) {
return node->val;
}
node = node->next;
}
return -1;
}
};
int main() {
HashTable ht(100); // 初始化哈希表,大小为100
ht.put("apple", 10); // 插入键值对
ht.put("banana", 20);
cout << "apple: " << ht.get("apple") << endl; // 查找键的值
cout << "banana: " << ht.get("banana") << endl;
cout << "orange: " << ht.get("orange") << endl;
return 0;
}
输出结果:
apple: 10
banana: 20
orange: -1
链式哈希是一种常用的数据结构,用于实现插入和查找操作时间复杂度为常数的键值对存储。我们可以通过C++的类和结构体来实现链表和哈希表,只要掌握了哈希函数的设计方法,就能轻松编写出高效的链式哈希表程序。