File size: 2,290 Bytes
4559903
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include "HashMap.h"
#include "PrimeChecker.h"

HashMap::HashMap(int size)
{
	while (!PrimeChecker::IsPrime(size)){
		size++;
	}
	size_ = size;
	map_ = new HashElement*[size_]();
}

HashMap::~HashMap()
{
	for (int i = 0; i < size_; i++){
		int hash = GetHash(i);
		if (!map_[hash]){
			continue;
		}
		HashElement *current_element = map_[hash];
		HashElement *next_element = map_[hash];
		while (next_element->next_element_){
			next_element = next_element->next_element_;
			delete current_element;
			current_element = next_element;
		}
		delete current_element;
	}
}

int HashMap::GetHash(int key) const{
	return key % size_;
}

void HashMap::Insert(int key, std::string value){
	int hash = GetHash(key);
	if (!map_[hash]){
		map_[hash] = new HashElement(key, value);
	}
	else{
		HashElement *last_element = map_[hash];
		while (last_element->next_element_){
			last_element = last_element->next_element_;
		}
		last_element->next_element_ = new HashElement(key, value);
	}
	count_++;
}

std::string HashMap::Find(int key) const{
	int hash = GetHash(key);
	if (map_[hash]){
		HashElement *current_element = map_[hash];
		while (current_element->GetKey() != key){
			current_element = current_element->next_element_;
		}
		return current_element->GetValue();
	}
	return nullptr;
}

bool HashMap::Contains(int key) const{
	int hash = GetHash(key);
	if (map_[hash]){
		HashElement *current_element = map_[hash];
		while (current_element->GetKey() != key && current_element->next_element_){
			current_element = current_element->next_element_;
		}
		if (current_element->GetKey() == key){
			return true;
		}
	}
	return false;
}

void HashMap::Remove(int key){
	if (!Contains(key)){
		return;
	}
	int hash = GetHash(key);
	HashElement *current_element = map_[hash];
	if (current_element->GetKey() == key){
		map_[hash] = current_element->next_element_;
		delete current_element;
	}
	else{
		HashElement *previous_element = current_element;
		current_element = current_element->next_element_;
		while (current_element->GetKey() != key){
			previous_element = current_element;
			current_element = current_element->next_element_;
		}
		previous_element->next_element_ = current_element->next_element_;
		delete current_element;
	}
	count_--;
}

int HashMap::GetCount() const{
	return count_;
}