Design a HashMap class in C++. Implement put, get methods.

要實現的HashMap結構如圖:
這裏寫圖片描述

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;
            }
        }
        return i;
    }
};

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章