-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathhashtable.cpp
More file actions
107 lines (94 loc) · 2.33 KB
/
hashtable.cpp
File metadata and controls
107 lines (94 loc) · 2.33 KB
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
102
103
104
105
106
107
/*Hash table with int as key and value both*/
#include <iostream>
#include <cstdlib>
using namespace std;
const int SIZE = 128;
class HashElement
{
public:
int key;
int value;
HashElement(int key, int value)
{
this->key = key;
this->value = value;
}
};
class HashTable
{
HashElement **table;
public:
HashTable();
~HashTable();
int hash(int key);
void insert(int key, int value);
int search(int key);
void remove(int key);
};
HashTable :: HashTable()
{
this->table = new HashElement* [SIZE];
for(int i=0; i<SIZE; i++) table[i] = NULL;
}
HashTable :: ~HashTable()
{
for(int i=0; i<SIZE; ++i)
{
if(table[i] != NULL) delete table[i];
//delete[] table;
}
}
int HashTable :: hash(int key){ return key%SIZE; }
void HashTable::insert(int key, int value)
{
int hashedkey = hash(key);
while(table[hashedkey]!=NULL && table[hashedkey]->key != key)
{
/*checking if the table has any HashElement at hashedkey index
and if the key value of that value matches*/
hashedkey = hash(hashedkey + 1);
//if it has the element, but key value doesn't match
}
if(table[hashedkey]!=NULL) //if hash table is full
delete table[hashedkey];
table[hashedkey] = new HashElement(key, value);
}
void HashTable::remove(int key)
{
int hashedkey = hash(key);
while(table[hashedkey]!=NULL)
{
if(table[hashedkey]->key==key) break;
hashedkey = hash(hashedkey+1);
}
if(table[hashedkey]==NULL)
{
cout << "No element at the key" << endl;
return;
}
else table[hashedkey]=NULL;
}
int HashTable::search(int key)
{
int hashedkey = hash(key);
while(table[hashedkey]!=NULL && table[hashedkey]->key!=key)
{
hashedkey = hash(hashedkey+1);
}
if(table[hashedkey]==NULL)
{
cout << "Nothing found for key "<< key << endl;
return -1; //Not found
}
return table[hashedkey]->value;
}
int main()
{
HashTable h;
h.insert(3,6);
cout << h.search(3) << endl;
h.remove(3);
cout << h.search(3) << endl;
h.insert(2048,10);
cout << h.search(2048) << endl;
}