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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值