template <typename KEY, typename VAL> struct HashNode {
KEY key;
VAL value;
HashNode* next;
HashNode() : next(NULL) {
}
HashNode(KEY key, VAL val) : key(key), value(val) {
next = NULL;
}
};
template <typename KEY, typename VAL> class HashMap {
private:
int size;
HashNode<KEY, VAL>* link;
int HashFun(KEY key) {
return (key*key) % size;
}
public:
HashMap() {
}
HashMap(int size) : size(size) {
link = new HashNode<KEY, VAL>[size];
}
void Dump(void) {
for (int i = 0; i < size; i++) {
HashNode<KEY, VAL>* f = link[i].next;
while (f != NULL) {
cout << f->key << " : " << f->value << endl;
f = f->next;
}
}
}
bool Find(KEY key, VAL& value) {
int hkey = HashFun(key);
HashNode* f = link[hkey].next;
while (f != NULL && f->key != key) {
f = f->next;
}
if (f != NULL) {
value = f->value;
return true;
} else {
return false;
}
}
void Delete(KEY key) {
int hkey = HashFun(key);
HashNode<KEY, VAL>* pre = &link[hkey];
HashNode<KEY, VAL>* cur = pre->next;
while (cur != NULL && cur->key != key) {
cur = cur->next;
pre = cur;
}
if (cur != NULL) {
pre->next = cur->next;
delete cur;
}
}
bool Insert(KEY key, VAL value) {
int hkey = HashFun(key);
HashNode<KEY, VAL>* f = link[hkey].next;
// if already exist;
while (f != NULL) {
if (f->key == key) {
f->value = value;
return true;
}
f = f->next;
}
// insert new node;
HashNode<KEY, VAL>* nn = new HashNode<KEY, VAL>(key, value);
nn->next = link[hkey].next;
link[hkey].next = nn;
return true;
}
};
hash_map 实现
最新推荐文章于 2022-08-31 17:46:46 发布