散列表(Hash Table),也叫哈希表或者哈希映射,是一种根据关键字直接访问内存位置的数据结构。散列表通过哈希函数将关键字映射到内存地址,从而实现快速的插入、删除和查找操作。
散列表的核心是哈希函数。哈希函数将关键字映射到一个固定大小的数组下标,这个下标就是该关键字在散列表中的位置。如果哈希函数设计得好,可以使得散列表的插入、删除和查找操作的时间复杂度都为O(1)。
散列表的优点是可以快速地进行查找、插入和删除操作,时间复杂度为O(1)。但是,散列表的缺点是需要消耗大量的内存空间,因为需要预留足够的空间来存储散列表。此外,散列表的性能取决于哈希函数的设计,如果哈希函数不好,会导致散列表的性能下降。
当然可以,以下是一个简单的用 C++ 实现散列表的代码:
```c++
#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
const int MAX_N = 10000; // 散列表最大容量
const int BASE = 131; // 哈希函数的基数
struct Node {
char key[100]; // 关键字
int value; // 值
Node *next; // 下一个节点指针
};
struct HashTable {
Node *data[MAX_N]; // 散列表数组
// 哈希函数
int hashFunc(char *key) {
int len = strlen(key);
int hashValue = 0;
for (int i = 0; i < len; i++) {
hashValue = hashValue * BASE + key[i];
}
return hashValue % MAX_N;
}
// 插入元素
void insert(char *key, int value) {
int hashValue = hashFunc(key);
Node *p = data[hashValue];
while (p != NULL) {
if (strcmp(p->key, key) == 0) {
p->value = value;
return;
}
p = p->next;
}
Node *newNode = new Node;
strcpy(newNode->key, key);
newNode->value = value;
newNode->next = data[hashValue];
data[hashValue] = newNode;
}
// 查找元素
int find(char *key) {
int hashValue = hashFunc(key);
Node *p = data[hashValue];
while (p != NULL) {
if (strcmp(p->key, key) == 0) {
return p->value;
}
p = p->next;
}
return -1; // 没有找到
}
// 删除元素
void remove(char *key) {
int hashValue = hashFunc(key);
Node *p = data[hashValue];
Node *pre = NULL;
while (p != NULL) {
if (strcmp(p->key, key) == 0) {
if (pre == NULL) {
data[hashValue] = p->next;
} else {
pre->next = p->next;
}
delete p;
return;
}
pre = p;
p = p->next;
}
}
};
int main() {
HashTable hashTable;
hashTable.insert("hello", 1);
hashTable.insert("world", 2);
hashTable.insert("good", 3);
hashTable.insert("morning", 4);
cout << hashTable.find("hello") << endl; // 打印 1
hashTable.remove("hello");
cout << hashTable.find("hello") << endl; // 打印 -1
return 0;
}
```
上述代码实现了散列表的基本操作,包括插入元素、查找元素和删除元素。具体实现过程中,使用了哈希函数将关键字映射到散列表中的位置,然后使用链表来解决哈希冲突的问题。