哈希表数据结构代码
时间: 2023-07-10 12:03:59 浏览: 63
哈希表是一种常用的数据结构,用于存储键值对,并且支持快速的插入、查找、删除操作。下面是一个简单的哈希表实现,使用线性探测法处理哈希冲突。
```c++
#include <iostream>
#include <string>
using namespace std;
const int TABLE_SIZE = 10;
class HashNode {
public:
int key;
string value;
HashNode(int key, string value) {
this->key = key;
this->value = value;
}
};
class HashMap {
private:
HashNode **table;
public:
HashMap() {
table = new HashNode*[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++) {
table[i] = nullptr;
}
}
~HashMap() {
for (int i = 0; i < TABLE_SIZE; i++) {
if (table[i] != nullptr) {
delete table[i];
}
}
delete[] table;
}
int hash(int key) {
return key % TABLE_SIZE;
}
void insert(int key, string value) {
int h = hash(key);
while (table[h] != nullptr && table[h]->key != key) {
h = (h + 1) % TABLE_SIZE;
}
if (table[h] != nullptr) {
delete table[h];
}
table[h] = new HashNode(key, value);
}
string find(int key) {
int h = hash(key);
while (table[h] != nullptr && table[h]->key != key) {
h = (h + 1) % TABLE_SIZE;
}
if (table[h] == nullptr) {
return "";
} else {
return table[h]->value;
}
}
void remove(int key) {
int h = hash(key);
while (table[h] != nullptr) {
if (table[h]->key == key) {
break;
}
h = (h + 1) % TABLE_SIZE;
}
if (table[h] == nullptr) {
return;
} else {
delete table[h];
table[h] = nullptr;
}
}
};
int main() {
HashMap map;
map.insert(1, "one");
map.insert(11, "eleven");
map.insert(21, "twenty-one");
cout << map.find(1) << endl;
cout << map.find(11) << endl;
cout << map.find(21) << endl;
map.remove(11);
cout << map.find(11) << endl;
return 0;
}
```
在上面的代码中,哈希表通过一个 HashNode 类来存储键值对,其中 key 是哈希表的键,value 是哈希表的值。HashMap 类实现了哈希表的基本操作,包括插入、查找、删除。哈希冲突采用线性探测法来解决。在插入操作时,如果哈希表中已经有相同的键,则先删除原来的节点,再插入新的节点。在查找和删除操作时,同样需要使用线性探测法来定位节点。