structure/HashTable.cpp
2023-07-19 16:44:50 +08:00

130 lines
3.0 KiB
C++

//
// Created by Administrator on 2023/7/19.
//
#include <cstdio>
#include <memory>
template <class T>
struct node_base {
T data;
node_base* last = nullptr;
node_base* next = nullptr;
};
template <class T, class T1>
class List {
public:
explicit List(size_t l = 10)
: node(new node_base<T>()), last(node), len(l), size(0) {
node_base<T>* for_old = nullptr;
node_base<T>* current = last;
for (int i = 0; i < len; ++i) {
if (i != 0)
current->last = for_old;
current->next = new node_base<T>();
for_old = current;
current = current->next;
}
}
void push_ele(T data) {
if (last->next != nullptr) {
last->data = data;
last = last->next;
} else {
node_base<T>* current = last;
for (int i = 0; i < len * 2; ++i) {
current->next = new node_base<T>();
current->next->last = current;
current = current->next;
}
len = len * 2;
last->data = data;
last = last->next;
}
++size;
}
size_t find(T& data, std::function<T1(T*)>& fun) {
node_base<T>* header = node;
for (int i = 0; i < size; ++i) {
if (fun(&node->data) == fun(&data)) {
node = header;
return i;
}
node = node->next;
if (node == nullptr) {
node = header;
return -1;
}
}
return -1;
}
private:
node_base<T>* node;
node_base<T>* last;
size_t len;
size_t size;
};
template <class K, class V>
struct pair {
K first;
V second;
};
template <class K, class V>
class HashMap {
public:
HashMap() : size(100) {
table = (List<pair<K, V>, K>**) malloc(sizeof( List<pair<K, V>, K>* ) * size);
for (int i = 0; i < size; ++i) {
table[i] = new List<pair<K, V>, K>();
}
}
virtual ~HashMap() {
for (int i = 0; i < size; ++i) {
delete table[i];
}
delete table;
}
public:
void insert(pair<K,V> ele) {
List<pair<K, V>, K>* list = table[buildHash(ele.first)];
list->push_ele(ele);
}
pair<K,V> find(K key) {
List<pair<K, V>, K>* list = table[buildHash(key)];
pair<K,V> pa = {key, ""};
std::function<V(pair<K,V>*)> fun = [&] (pair<K,V>* ele) {
if (ele != &pa) {
pa.second = ele->second;
}
return ele->first;
};
list->find(pa, fun);
return pa;
}
private:
size_t buildHash(K key) {
std::hash<K> hash;
return hash(key) % size;
}
private:
size_t size;
List<pair<K, V>, K>** table;
};
int main () {
HashMap<std::string, std::string> hashMap;
hashMap.insert({"one", "exe haha"});
auto item = hashMap.find("one");
printf("%s", item.second.c_str());
}