#include<bits/stdc++.h>
using namespace std;
class Node{
public:
int val;
int key;
Node* next;
Node(int key, int val):key(key), val(val), next(NULL){}
};
class MyHashMap {
private:
int tablesize;
Node* HashTable[];
public:
/** Initialize your data structure here. */
MyHashMap() {
tablesize = 100;
for(int i=0; i<tablesize; i++)
HashTable[i] = NULL;
}
/** value will always be non-negative. */
void put(int key, int value) {
int index = key % 100;
Node* np = new Node(key, value);
if(np == NULL) return ;
np->next = HashTable[index];
HashTable[index] = np;
}
/** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
int get(int key) {
int index = key % 100;
Node* np = HashTable[index];
while( np != NULL){
if(np->key == key)
return np->val;
np = np->next;
}
return -1;
}
/** Removes the mapping of the specified value key if this map contains a mapping for the key */
void remove(int key) {
int index = key % 100;
Node* np = HashTable[index];
Node* prev = NULL;
if(!np)
return ;
while(np){
if(np->key == key){
if(prev == NULL)
HashTable[index] = np->next;
else
prev->next = np->next;
delete np;
break;
}
prev = np;
np = np->next;
}
}
};
/**
* Your MyHashMap object will be instantiated and called as such:
* MyHashMap obj = new MyHashMap();
* obj.put(key,value);
* int param_2 = obj.get(key);
* obj.remove(key);
*/
int main(){
MyHashMap* obj = new MyHashMap();
obj->put(1,1);
obj->put(2,4);
obj->put(3,5);
int ans = obj->get(1);
cout<<ans<<endl;
obj->remove(1);
cout<<obj->get(1)<<endl;
cout<<obj->get(3)<<endl;
}
}
拉链法Hash简易实现
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 上一章,简单介绍了Hash Table,并提出了本教程中要实现的几个Hash Table的方法,有search(a...
- 说明 Hash table翻译过来就是Hash表,是一种提供了类似于关联数组的数据结构,可以通过key执行搜索、插...
- 上一章中,我们使用了双重Hash的技术来处理碰撞,并用了C语言实现,本章我们将实现Hash表中的插入、搜索和删除接...
- 上一章中,我们实现了Hash表中的插入、搜索和删除接口,我们在初始化hash表时固定了大小为53,为了方便扩展,本...
- 上一章,我们讲了hash表的数据结构,并简单实现了hash表的初始化与删除操作,这一章我们会讲解Hash函数和实现...