-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashTableVoid.cc
120 lines (105 loc) · 2.74 KB
/
HashTableVoid.cc
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
108
109
110
111
112
113
114
115
116
117
118
119
//
// Implementation of a HashTable that stores void *
//
#include "HashTableVoid.h"
#include <stdio.h>
// Obtain the hash code of a key
int HashTableVoid::hash(const char * key)
{
int sum = 0;
// Add implementation here
while (*key) {
sum += *key;
key++;
}
return sum % 2039;
}
// Constructor for hash table. Initializes hash table
HashTableVoid::HashTableVoid()
{
// Add implementation here
_buckets = (HashTableVoidEntry **) malloc(TableSize * sizeof(HashTableVoidEntry*));
for (int i = 0; i < TableSize; i++) {
_buckets[i] = NULL;
}
}
// Add a record to the hash table. Returns true if key already exists.
// Substitute content if key already exists.
bool HashTableVoid::insertItem( const char * key, void * data)
{
// Add implementation here
int h = hash(key);
HashTableVoidEntry * e = _buckets[h];
while (e != NULL) {
if (!strcmp(e->_key, key)) {
e->_data = data;
return true;
}
e = e->_next;
}
e = new HashTableVoidEntry;
e->_key = strdup(key);
e->_data = data;
e->_next = _buckets[h];
_buckets[h] = e;
return false;
}
// Find a key in the dictionary and place in "data" the corresponding record
// Returns false if key is does not exist
bool HashTableVoid::find( const char * key, void ** data)
{
// Add implementation here
int h = hash(key);
HashTableVoidEntry * e = _buckets[h];
while (e != NULL) {
if (!strcmp(e->_key, key)) {
*data = e->_data;
return true;
}
e = e->_next;
}
return false;
}
// Removes an element in the hash table. Return false if key does not exist.
bool HashTableVoid::removeElement(const char * key)
{
// Add implementation here
int h = hash(key);
HashTableVoidEntry * e = _buckets[h];
HashTableVoidEntry * prev = NULL;
while (e != NULL) {
if (!strcmp(e->_key, key)) {
if (prev != NULL) {
prev->_next = e->_next;
} else {
_buckets[h] = e->_next;
}
delete e;
return true;
}
prev = e;
e = e->_next;
}
return false;
}
// Creates an iterator object for this hash table
HashTableVoidIterator::HashTableVoidIterator(HashTableVoid * hashTable)
{
// Add implementation here
_hashTable = hashTable;
_currentEntry = _hashTable->_buckets[0];
_currentBucket = 0;
}
// Returns true if there is a next element. Stores data value in data.
bool HashTableVoidIterator::next(const char * & key, void * & data)
{
for (; _currentBucket < 2039; _currentBucket++) {
if((_currentEntry = _hashTable->_buckets[_currentBucket]) != NULL) {
data = _currentEntry->_data;
key = _currentEntry->_key;
_currentBucket++;
return true;
}
}
return false;
}