要实现的HashMap结构如图:
![](https://img.haomeiwen.com/i5909658/636c2df0d3029167.jpg)
Code:
// Compiled with: g++ -Wall -std=c++14 -pthread
#include <iostream>
#include <string>
using namespace std;
class HashMap {
typedef struct entry {
unsigned int key;
string value;
entry* next;
unsigned int hash;
} entry;
entry* Bucket[16] = {nullptr};
public:
void Put(const unsigned int key, const string& value) {
unsigned int ind = key%16;
entry* i;
for (i = Bucket[ind]; i != nullptr; i = i->next) {
if (i->key == key) {
i->value = value;
break;
}
}
if (i == nullptr) {
entry *node = new entry();
node->key = key;
node->value = value;
node->next = Bucket[ind];
node->hash = ind;
Bucket[ind] = node;
}
}
entry* Get(const unsigned key) {
unsigned int ind = key%16;
entry* i;
for (i = Bucket[ind]; i != nullptr; i = i->next) {
if (i->key == key) {
break;
}
}
if (i != nullptr) {
return i;
}
else {
return nullptr;
}
}
};
int main(){
HashMap hashmap;
hashmap.Put(0, "hello");
hashmap.Put(1, "HELLO");
hashmap.Put(18, "hEllo18");
hashmap.Put(16, "hello16");
hashmap.Put(17, "world");
unsigned int testkey = 0;
if (!hashmap.Get(testkey)) {
cout << "no found" << endl;
}
else {
cout << hashmap.Get(testkey)->value << endl;
}
cout << "Hello, World!" << endl;
return 0;
}
网友评论