拉链法Hash简易实现

#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;
 }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容